如何强制特定网络适配器上的流量

时间:2014-10-28 18:21:13

标签: c# windows azure network-programming

我正在开发一个控制台应用程序作为我的web-api的客户端,例如谷歌驱动器和天空驱动器等......我遇到了一个边缘案例:我的电脑有2个连接:以太网和wifi 以太网在代理后面,无线网络是开放的 这里的问题是以太网在代理后面,阻止了我的alpha测试的公共地址(在windows azure中)。

因为windows似乎总是只相信以太网,这是令人沮丧的,因为如果它只尝试wifi,它会工作......我想知道我该怎么做才能强制打开使用我的第二个网络适配器的套接字(WIFI)。

2 个答案:

答案 0 :(得分:3)

Shtééf's anwserHow does a socket know which network interface controller to use?MSDN Socket reference相结合可提供以下信息:

假设PC有两个接口:

  • Wifi:192.168.22.37
  • 以太网:192.168.1.83

按如下方式打开套接字:

`

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。 对于后者,您可以查看How to use socket based client with WCF (net.tcp) service?以获取有关如何实现自己的传输的指示。

答案 1 :(得分:1)

您需要将出站套接字连接绑定到正确的网络接口,请参阅此SO帖子: How does a socket know which network interface controller to use?