[英]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".我在 MacOS 机器上有 2.network 接口:“ZTE Mobile Broadband”和“Ethe.net”。 Both can be used to access the Inte.net.
两者都可以用来访问Inte.net。 Is it possible to influence how a specific URL will be requested from
node.js
?是否有可能影响从
node.js
请求特定 URL 的方式? Eg got('https://ifconfig.co', {/* something to mark traffic to make the OS send this specific request over eth or zte */})
?例如
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?我知道您可以添加路由以通过特定接口请求特定目的地,并且您可以标记来自某个进程 ID 的流量,然后使来自该进程的所有流量 go 通过特定接口,但是来自进程的单个请求呢?
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现在我无法测试你的确切场景,但你可以尝试将你想要使用的接口的 IP 设置为
localAddress
选项中所指出的这个答案
or providing a custom agent
as exemplified in this workaround或提供此解决方法中举例说明的自定义
agent
@user2226755 for the bounty "Do you know a way to do a HTTP request in node over a specific interface?" @user2226755赏金“你知道通过特定接口在节点中执行 HTTP 请求的方法吗?”
the "specific" interface is specified in the form of the provided ip address. “特定”接口以提供的 ip 地址的形式指定。
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.然后,就像 Franco Rondini 所说的那样,根据这个github 问题线程使用自定义代理。
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:没有 axios:
https://stackoverflow.com/a/20996813/4935162 https://stackoverflow.com/a/20996813/4935162
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.