Phani Kumar
Phani Kumar

Reputation: 450

Specify local port for TCP socket client connection

How to specify the source port/local port for outbound TCP connection using node.js? This is required to support certain firewall rules.

net.connect({port: PORT, host: HOST}, callback)

I expect an additional parameter 'localPort' in the above call. But looks the API doesn't handle and the following doesn't work.

net.connect({port: PORT, host: HOST, localPort: 12345}, callback)

Using Java I would do like below:

Socket s = new Socket();
s.bind(new InetSocketAddress("179.11.123.102", 5000));
s.connect(new InetSocketAddress("178.1.2.102", 1234));

What is equivalent in node.js?

Upvotes: 6

Views: 2711

Answers (1)

apsillers
apsillers

Reputation: 115970

According to the bug report "net.connect() should accept a localPort option", the feature was recently added:

Currently, net.connect has a parameter localAddress, but it should also have a localPort...

It's just not released yet... [it] should be included in v0.11.13

It was added in this commit on February 17 and should be available in the next release of Node. If you can't wait, you can patch the diff directly into 0.10.31, and it should work as-is because the C++ Bind function at the time of the 0.10.31 release supports a port argument (the patch simply augments the JavaScript layer to use that C++ argument).

Upvotes: 6

Related Questions