What is socks?
The 'socks' npm package is a comprehensive Node.js library for working with SOCKS proxies. It supports SOCKS v4, v4a, and v5 protocols and can be used to create both SOCKS proxy clients and servers. It allows for proxying TCP and UDP connections, handling DNS lookups, and provides a way to work with different authentication methods.
What are socks's main functionalities?
Creating a SOCKS client
This code sample demonstrates how to create a SOCKS client that connects to a specified destination through a SOCKS proxy server.
const { SocksClient } = require('socks');
const options = {
proxy: {
host: 'host', // ipv4, ipv6, or hostname
port: 1080,
type: 5 // Proxy version (4, 5)
},
command: 'connect',
destination: {
host: 'destinationHost',
port: 80
}
};
SocksClient.createConnection(options, (err, info) => {
if (err) {
console.log(err);
return;
}
const socket = info.socket;
console.log('Connected to server through SOCKS proxy');
});
Creating a SOCKS server
This code sample shows how to create a SOCKS server that listens for incoming connections and can handle custom authentication.
const socks = require('socks').SocksServer;
const server = new socks({
proxy: {
ipaddress: 'localhost',
port: 1080,
type: 5
},
authenticate: function(username, password, socket, callback) {
// Custom authentication logic
callback();
}
});
server.listen();
server.on('proxyConnect', (info, destinationSocket) => {
console.log(`Accepted connection to ${info.host}:${info.port}`);
});
Handling UDP connections
This code sample illustrates how to handle UDP connections through a SOCKS proxy using the 'associate' command.
const { SocksClient } = require('socks');
const options = {
proxy: {
host: 'host',
port: 1080,
type: 5
},
command: 'associate',
destination: {
host: '0.0.0.0', // The local interface to bind for UDP association
port: 0 // A random port will be used
}
};
SocksClient.createConnection(options, (err, info) => {
if (err) {
console.log(err);
return;
}
const udpSocket = info.socket;
console.log('UDP association has been established.');
});
Other packages similar to socks
node-socks-proxy-agent
This package is similar to 'socks' in that it provides SOCKS proxy support for HTTP and HTTPS requests. It is specifically designed to work with the 'agent-base' API, making it easy to integrate with the built-in 'http' and 'https' modules in Node.js.
socksv5
The 'socksv5' package is another Node.js module that provides similar functionality to 'socks'. It supports the SOCKS v5 protocol and can be used to create both SOCKS clients and servers. It also supports GSS-API authentication, which is not available in the 'socks' package.
http-proxy-agent
While not limited to SOCKS proxies, 'http-proxy-agent' allows Node.js HTTP clients to proxy requests through a specified server. It supports HTTP, HTTPS, and SOCKS proxies, providing a broader range of proxy support compared to the 'socks' package.