Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify local port for TCP socket client connection

Tags:

node.js

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?

like image 578
Phani Kumar Avatar asked Sep 03 '14 10:09

Phani Kumar


1 Answers

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).

like image 178
apsillers Avatar answered Sep 20 '22 01:09

apsillers