简体   繁体   中英

How to force traffic on specific network adapter

I'm developing a console app to act as a client for my web-api, such as google drive, and sky drive and etc... And I ran into a edge case: my pc has 2 connections: a Ethernet and a wifi.
The Ethernet is behind a proxy and the wifi is open.
The problem here is that the ethernet is behind a proxy, that blocks the public address for my alpha tests (in windows azure).

Since windows seems to always believe only in the ethernet, which is frustrating because if it would only try the wifi, it would work... I was wondering what can i do to force to open the socket using my second network adapter (wifi).

Combining Shtééf's anwser to How does a socket know which network interface controller to use? and the MSDN Socket reference gives the following:

Suppose the PC has two interfaces:

  • Wifi: 192.168.22.37
  • Ethernet: 192.168.1.83

Open a socket as follows:

`

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();
}

NOTE: Using a Socket like this is somewhat low level. I could not find how to easily use Sockets —bound to a local endpoint— with higher level facilities such as HttpClient or the WCF NetHttpBinding . For the latter you could look at How to use socket based client with WCF (net.tcp) service? for pointers how to implement your own transport.

您需要将出站套接字连接绑定到正确的网络接口,请参阅此SO帖子: 套接字如何知道要使用哪个网络接口控制器?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM