簡體   English   中英

如何從 node.js 通過特定的外部網絡接口發送流量?

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

我在 MacOS 機器上有 2.network 接口:“ZTE Mobile Broadband”和“Ethe.net”。 兩者都可以用來訪問Inte.net。 是否有可能影響從node.js請求特定 URL 的方式? 例如got('https://ifconfig.co', {/* something to mark traffic to make the OS send this specific request over eth or zte */})

我知道您可以添加路由以通過特定接口請求特定目的地,並且您可以標記來自某個進程 ID 的流量,然后使來自該進程的所有流量 go 通過特定接口,但是來自進程的單個請求呢?

現在我無法測試你的確切場景,但你可以嘗試將你想要使用的接口的 IP 設置為localAddress選項中所指出的這個答案

或提供此解決方法中舉例說明的自定義agent

@user2226755賞金“你知道通過特定接口在節點中執行 HTTP 請求的方法嗎?”

“特定”接口以提供的 ip 地址的形式指定。

你可以用類似的東西得到它

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

或者

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

然后,就像 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

沒有 axios:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM