给socks-proxy-agent增加认证

由于需要使用socks代理,查看了nodejs的各种socks库,最终的结论是socks库是其中最完善的,而socks-proxy-agent是以其为基础的封装,可以直接和http模块对接。

不过在尝试后发现socks-proxy-agent建立的连接无法使用认证功能,而直接使用socks库是可以的。因此查看了其源码。

  var options = {
    proxy: {
      ipaddress: proxy.host,
      port: proxy.port,
      type: proxy.version
    },
    target: {
      port: opts.port
    },
    command: 'connect'
  };

  if (proxy.lookup) {
    // client-side DNS resolution for "4" and "5" socks proxy versions
    dns.lookup(opts.host, onlookup);
  } else {
    // proxy hostname DNS resolution for "4a" and "5h" socks proxy servers
    options.target.host = opts.host;
    SocksClient.createConnection(options, onhostconnect);
  }
}

可见options只选用了地址,端口,类型,等少数参数,认证参数不在其中。

按照socks的说明

socks5的认证参数为:

options.proxy.authentication={"username":string,"password":string};

socks4的用户id为://socks4不支持密码。

options.proxy.userid=string;

于是添加了一段

  if (proxy.auth){
    var auth=proxy.auth.split(":");
    var optp=options.proxy;
    optp.authentication={"username":auth[0],"password":auth[1]};
    optp.userid=auth[0];
  }

连接socks5成功了,连接socks4失败,显示:"Error: Socket Closed",这样的效果和直接使用socks相同,所以显然问题在于socks库本身(测试的服务器是ccproxy)。

目标已经达到了,收工。

修改已经提交至github:https://github.com/hjiayz/node-socks-proxy-agent

原文地址:https://www.cnblogs.com/XmodYgetZ/p/4549280.html