简体   繁体   中英

How to send traffic over a specific external network interface from node.js?

I have 2.network interfaces on a MacOS machine: "ZTE Mobile Broadband" and "Ethe.net". Both can be used to access the Inte.net. Is it possible to influence how a specific URL will be requested from node.js ? Eg got('https://ifconfig.co', {/* something to mark traffic to make the OS send this specific request over eth or zte */}) ?

I know you can add routes to request specific destinations over specific interfaces, and that you can mark traffic from a certain process id and then make all traffic from this process go over specific interface, but what about single requests from a process?

now I can't test your exact scenario, but you could try setting the IP of the interface you'd like to use into the localAddress option as pointed in this answer

or providing a custom agent as exemplified in this workaround

@user2226755 for the bounty "Do you know a way to do a HTTP request in node over a specific interface?"

the "specific" interface is specified in the form of the provided ip address.

you could get it with somthing like

import { networkInterfaces } from 'os';
const interfaces = networkInterfaces();
...

or

const interface_ip = require('os').networkInterfaces()['Ethernet']['address'] // Ethernet being NIC name.

then, like Franco Rondini said, use a custom agent, per this github issue thread.

const http = require('http')
const https = require('https')
const options = { localAddress: interface_ip, /* taken from networkInterfaces() */ /* family: 4 // optional for ipv4, but set to 6 if you use ipv6 */ }
const httpAgent = new http.Agent(options)
const httpsAgent = new https.Agent(options)
axios.get('https://example.com/', { httpAgent, httpsAgent })
// you don't have to use both http and https if you know which of these protocols the website is using

and without axios:

https://stackoverflow.com/a/20996813/4935162

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM