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

net.connect there an option in http.request or net.connect to specify a network interface to initiate a connection?

EDIT: AFAIK at OS level. I can specify the address level or load balancing in the routing tables. But the way to choose an interface in my software is, moreover, I want to know if I can do this in codes.

+7
source share
3 answers

Node has a built-in function:

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 it for the IP interface of the interface you want to use.

+3
source

EDIT . As Mac noted, it's really possible to specify a network interface from a user process. I stand fixed. However, I have not yet found a module that allows it using node.

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

You can list this table with netstat -r on Unix systems (including OSX). Just open a terminal and enter the command. You will get a list, for example:

 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 displays the network interface used for the route. You can also get the interface used to reach the host name using 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 of a server problem, but you can change routes using the route command. For example, this will direct traffic to XYZ [0-254] to XYZ254 to eth0:

 route add -net XYZ0/24 gw XYZ254 dev eth0 

If you want the routes to be preserved on 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
source

You can use node cURL wrapper

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

All Articles