Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 "Ethernet". Both can be used to access the Internet. Is it possible to influence how a specific URL will be requested from node.js? E.g. 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?

like image 828
eeeeeeeeeeeeeeeeeeeeeeeeeeeeee Avatar asked Nov 02 '25 11:11

eeeeeeeeeeeeeeeeeeeeeeeeeeeeee


1 Answers

@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

like image 58
Yarin_007 Avatar answered Nov 04 '25 08:11

Yarin_007