I want to know how it is possible to open simply a socket on a specific interface (eth0, wlan0, ...) in Node JS.
我想知道如何在Node JS中的特定接口(eth0,wlan0,...)上打开一个套接字。
It seems to be possible in C and possible also with ping command with ping -I eth0 google.com
.
它似乎可以在C中使用ping -I eth0 google.com的ping命令。
But how to do that with Node JS ? I have seen nothing in net.Socket documentation.
但是如何使用Node JS做到这一点?我在net.Socket文档中没有看到任何内容。
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"});
我找到了一些包装动态库的代码,但应该有一种更简单的方法。不是吗?像socket.connect({host:“google.com”,port:80,interface:“eth0”});
1 个解决方案
#1
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.
net.Socket.connect(options [,connectListener])接受localAddress参数,该参数指定套接字应从哪个地址连接。每个物理接口都只有一个IP地址*。因此,正确的方法是确定您要使用的接口的IP地址,并在连接呼叫中使用IP。
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.
然后操作系统将确定接口(在这种情况下为eth0)。有点麻烦,但是当更高级别可用时,这是避免处理较低级别地址的通常模式。
* - a little bit more if IPv6 is also configured, but this is rarely a problem.
* - 如果还配置了IPv6,可以多一点,但这很少是一个问题。
#1
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.
net.Socket.connect(options [,connectListener])接受localAddress参数,该参数指定套接字应从哪个地址连接。每个物理接口都只有一个IP地址*。因此,正确的方法是确定您要使用的接口的IP地址,并在连接呼叫中使用IP。
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.
然后操作系统将确定接口(在这种情况下为eth0)。有点麻烦,但是当更高级别可用时,这是避免处理较低级别地址的通常模式。
* - a little bit more if IPv6 is also configured, but this is rarely a problem.
* - 如果还配置了IPv6,可以多一点,但这很少是一个问题。