Is there a way to set the source port for a node js https request?

Is there a way to set the source port for a node js https request? I am not asking about the destination, not the source, that is, the port used to send the request.

In the context, I am trying to send https requests from a specific port, and not from random ports, which allows iptables to be blocked. node does not work as root, so the port is not 443.

Update: There seems to be a bug in Node. The localAddress and localPort parameters do not work, at least with a TLS socket.

Update: Found a similar question from last year. The answers were “don't do this,” which seems dumb, given that node is a common tool. Nodejs TCP Client Port Assignment

+2
source share
2 answers

Unfortunately, it seems that Node does not support client port binding. Apparently, this is not a feature that is used a lot, but it is possible. This link explains port binding very well. https://blog.cloudflare.com/cloudflare-now-supports-websockets/ Not sure how to get nodejs people to consider this change.

0
source

The function seems undocumented, but you can achieve this by installing BOTH options localAddressand localPortfor options in the argument https.request.

For more information, see the code here: https://github.com/nodejs/node/blob/b85a50b6da5bbd7e9c8902a13dfbe1a142fd786a/lib/net.js#L916

The following is a basic example:

var https = require('https');

var options = {
  hostname: 'example.com',
  port: 8443,
  localAddress : '192.168.0.1',
  localPort: 8444
};

var req = https.request(options, function(res) {
    console.log(res);
});

req.end();
+1
source

All Articles