1

I want to know how it is possible to open simply a socket on a specific interface (eth0, wlan0, ...) in Node JS.

It seems to be possible in C and possible also with ping command with ping -I eth0 google.com.

But how to do that with Node JS ? I have seen nothing in net.Socket documentation.

I have found some code that wrap dynamic library but there should be a easier way to do that. No ? Something like socket.connect({host :"google.com", port:80, interface:"eth0"});

doom
  • 3,276
  • 4
  • 30
  • 41

1 Answers1

0

net.Socket.connect(options[, connectListener]) accepts localAddress parameter which specifies what address the socket should connect from. Each your physical interface has exactly one IP address attached to it*. So the proper way would be to determine an IP address of the interface you'd like to use and use the IP in connect call.

socket.connect({
    host: "google.com",
    port: 80,
    localAddress: somehowGetIPv4AddrOfInterface("eth0"),
 });

The OS will then determine the interface (eth0 in this case). A bit cumbersome, but it is a usual pattern to avoid dealing with lower level addresses when a higher level is available.

* - a little bit more if IPv6 is also configured, but this is rarely a problem.

u354356007
  • 3,205
  • 15
  • 25
  • hello. thanks for your answer. can you say more things about ipv6? – kodmanyagha Apr 15 '20 at 16:05
  • @kodmanyagha sorry, but I don't remember the details. I probably meant specifying `family` option (see the docs), or making sure some sort of local IPv6 is assigned to the interface (e. g. `ifconfig`). – u354356007 Apr 16 '20 at 22:25