Mat.C
Mat.C

Reputation: 1439

How to check if a proxy works in JavaScript

I'm trying to do a proxy checker in JavaScript. I give input the proxy data and it checks if the proxy works.

For now I wrote this function using the request module of Node.js.

const  request = require('request');

var checkProxy = function(id, ip, port, url, user, pass, callback) {

    let proxy_url;
    if (user){
        if (user != ''){
            proxy_url = `socks5://${user}:${pass}@${ip}:${port}`;
        }
    } else {
        proxy_url = 'socks5://' + ip + ':' + port;
        console.log(proxy_url)
    }


    var proxyRequest = request.defaults({
        proxy: proxy_url,
    });

    proxyRequest({url: url, timeout: 120000}, function(err, res) {
        var testText = 'content="Brum Brum ..."';
        if( err ) {

            callback(id, ip, port, false, -1, err);
        } else if( res.statusCode != 200 ) {
            callback(id, ip, port, false, res.statusCode, err);
        } else if( !res.body ) {
            callback(id, ip, port, false, res.statusCode, "regex problem" + options.regex + ".");
        } else {
            callback(id, ip, port, true, res.statusCode);
        }

    });
}

As callback I pass:

() => {console.log(id, ip, port, false, res.statusCode, err);}

But when I try to check an IP address it gives wrong results. I took proxy from this site (proxy: 207.154.231.217:1080) and checked it with the function, but in the callback console.log I got the current error:

ERROR: proxy num: 0, ip: 207.154.231.217, port: 1080, STATUS: -1, ERROR: Error: tunneling socket could not be established, cause=socket hang up

I read that this is for some sort of authentication required, but I don't understand why if I check it on this site, the sites tell me that the proxy works.

I'm using:

Upvotes: 4

Views: 9551

Answers (1)

Yaroslav Gaponov
Yaroslav Gaponov

Reputation: 2109

Install the socks5-http-client module and run this code:

const request = require('request');
const Agent = require('socks5-http-client/lib/Agent');


var checkProxy = function (id, ip, port, url, user, pass, callback) {

    var proxyRequest = request.defaults({
        agentClass: Agent,
        agentOptions: {
            socksHost: ip,
            socksPort: port,
            socksUsername: user,
            socksPassword: pass
        }
    });

    proxyRequest({ url: url, timeout: 120000 }, function (err, res) {
        var testText = 'content="Brum Brum ..."';
        if (err) {

            callback(id, ip, port, false, -1, err);
        } else if (res.statusCode != 200) {
            callback(id, ip, port, false, res.statusCode, err);
        } else if (!res.body) {
            callback(id, ip, port, false, res.statusCode, "regex problem" + options.regex + ".");
        } else {
            callback(id, ip, port, true, res.statusCode);
        }

    });
}

Upvotes: 3

Related Questions