Leonardo
Leonardo

Reputation: 11391

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).

Upvotes: 3

Views: 10140

Answers (2)

Kasper van den Berg
Kasper van den Berg

Reputation: 9526

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.

Upvotes: 3

Erik Oppedijk
Erik Oppedijk

Reputation: 3553

You will need to bind the outbound socket connection to the correct network interface, see this SO post: How does a socket know which network interface controller to use?

Upvotes: 1

Related Questions