Choose one of many Internet connections for an application

This is somewhat advanced functionality which is abstracted away by both HttpWebRequest, WebRequest, WebClient and the like. You can, however, do this using TcpClient (using the constructor taking a local endpoint) or using sockets and calling Socket.Bind.

Use the Bind method if you need to use a specific local endpoint. You must call Bind before you can call the Listen method. You do not need to call Bind before using the Connect method unless you need to use a specific local endpoint.

Bind to a local endpoint for the interface you want to use. If your local machine have ip address 192.168.0.10 for the WiFi address, then using that a local endpoint will force sockets to use that interface. Default is unbound (really 0.0.0.0) which tells the network stack to resolve the interface automatically, which you want to circumvent.

Here’s some example code based on Andrew’s comment. Note that specifying 0 as local endpoint port means that it is dynamic.

using System.Net;
using System.Net.Sockets;

public static class ConsoleApp
{
    public static void Main()
    {
        {
            // 192.168.20.54 is my local network with internet accessibility
            var localEndPoint = new IPEndPoint(IPAddress.Parse("192.168.20.54"), port: 0);
            var tcpClient = new TcpClient(localEndPoint);

            // No exception thrown.
            tcpClient.Connect("stackoverflow.com", 80);
        }
        {
            // 192.168.2.49 is my vpn, having no default gateway and unable to forward
            // packages to anything that is outside of 192.168.2.x
            var localEndPoint = new IPEndPoint(IPAddress.Parse("192.168.2.49"), port: 0);
            var tcpClient = new TcpClient(localEndPoint);

            // SocketException: A socket operation was attempted to an unreachable network 64.34.119.12:80
            tcpClient.Connect("stackoverflow.com", 80);
        }
    }
}

Leave a Comment