How to specify a network interface when making net requests from Node.js?

只谈情不闲聊 提交于 2019-12-29 05:26:26

问题


In either http.request or net.connect, is there an option that I can specify a network interface to initiate a connection?

EDIT: AFAIK in OS level I can specify address level, or load balancing into routing tables. But the way of interface choosing in my software is more than that, I wanna know if I can do that in codes.


回答1:


Node has this built in:

http://nodejs.org/api/net.html#net_net_connect_options_connectionlistener

http://nodejs.org/api/http.html#http_http_request_options_callback

See localAddress, just set that to the IP of the interface you'd like to use.




回答2:


EDIT: As mak pointed out, it is indeed possible to specify a network interface from a user process. I stand corrected. However, I haven't yet found a module that allows it with node.

By default, the network interface is determined by the OS routing table.

You can list this table with netstat -r on Unix systems (OSX included). Just open a terminal and type the command. You will get a listing like:

laurent ~ $ netstat -r
Routing tables

Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
default            192.168.1.1        UGSc          153        0     en0
127                localhost          UCS             0        0     lo0
localhost          localhost          UH              2       42     lo0
...

The Netif field gives you the network interface used for the route. You can also get the interface used to reach a hostname with route:

laurent ~ $ route get google.fr
   route to: par03s02-in-f23.1e100.net
destination: default
       mask: default
    gateway: 192.168.1.1
  interface: en0
      flags: <UP,GATEWAY,DONE,STATIC,PRCLONING>
 recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire
       0         0         0         0         0         0      1500         0 

This is more a serverfault thing, but you can change routes with the route command. For example, this will route traffic to X.Y.Z.[0-254] to X.Y.Z.254 on eth0:

route add -net X.Y.Z.0/24 gw X.Y.Z.254 dev eth0

If you want routes to persist a reboot, you can add them to /etc/network/interfaces. If you want to load balance between several different routes, you should also check MPLS.




回答3:


You can use node cURL wrapper

curl = require('node-curl')
curl('www.google.com', { INTERFACE: 'eth1', RAW: 1 }, function(err) {
    console.info(this);
});


来源:https://stackoverflow.com/questions/13602066/how-to-specify-a-network-interface-when-making-net-requests-from-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!