[英]How to force traffic on specific network adapter
我正在开发一个控制台应用程序作为我的web-api的客户端,如谷歌驱动器和天空驱动器等...我遇到了一个边缘案例:我的电脑有2个连接:一个以太网和一个wifi 。
以太网在代理后面,wifi是开放的。
这里的问题是以太网在代理后面,阻止了我的alpha测试的公共地址(在windows azure中)。
因为windows似乎总是只相信以太网,这是令人沮丧的,因为如果它只尝试wifi,它会工作......我想知道我该怎么做才能强制打开使用我的第二个网络适配器(wifi)的套接字。
将Shtééf的 anwser与socket如何知道使用哪个网络接口控制器相结合? 和MSDN套接字引用提供以下内容:
假设PC有两个接口:
打开套接字如下:
Socket.Bind(EndPoint)
选择要使用的本地网络接口; Socket.Connect(EndPoint)
连接到远程服务。 `
using System.Net.Sockets;
using System.Net;
void Main()
{
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
int anyPort = 0;
EndPoint localWifiEP = new IPEndPoint(new IPAddress(new byte[] { 192, 168, 22, 37 }), anyPort);
EndPoint localEthernetEP = new IPEndPoint(new IPAddress(new byte[] { 192, 168, 1, 82 }), anyPort);
clientSock.Bind(localWifiEP);
// Edit endpoint to connect to an other web-api
// EndPoint webApiServiceEP = new DnsEndPoint("www.myAwsomeWebApi.org", port: 80);
EndPoint webApiServiceEP = new DnsEndPoint("www.google.com", port: 80);
clientSock.Connect(webApiServiceEP);
clientSock.Close();
}
注意:使用这样的Socket有点低级别。 我找不到如何轻松地使用Sockets -bound到本地端点 - 使用更高级别的设施,如HttpClient
或WCF NetHttpBinding
。 对于后者,您可以查看如何使用基于套接字的客户端和WCF(net.tcp)服务? 指针如何实现自己的传输。
您需要将出站套接字连接绑定到正确的网络接口,请参阅此SO帖子: 套接字如何知道要使用哪个网络接口控制器?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.