为应用程序选择许多Internet连接之一

Tal*_*ode 16 c# network-programming

我有一台电脑,有几个不同的互联网连接.LAN,WLAN,WiFi或3G.所有这些都是活动的,机器可以使用它们中的任何一个.

现在我想告诉我的应用程序使用一个可用的连接.例如,我想告诉我的应用程序只使用WiFi,而其他软件可能会使用其他东西.

在我的c#应用程序中,我使用类似HttpWebRequest和的类HttpWebResponse.

这甚至可能吗?

sis*_*sve 20

这是一些先进的功能,它被HttpWebRequest,WebRequest,WebClient等抽象出来.但是,您可以使用TcpClient(使用构造函数获取本地端点)或使用套接字并调用Socket.Bind来执行此操作.

如果需要使用特定的本地端点,请使用Bind方法.您必须先调用Bind才能调用Listen方法.除非需要使用特定的本地端点,否则在使用Connect方法之前无需调用Bind.

绑定到要使用的接口的本地端点.如果您的本地计算机的IP地址为IP地址192.168.0.10,则使用该地址端点将强制套接字使用该接口.默认为未绑定(实际为0.0.0.0),它告诉网络堆栈自动解析接口,您要绕过该接口.

这是基于Andrew评论的一些示例代码.请注意,将0指定为本地端点端口意味着它是动态的.

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


dgv*_*vid 10

请参阅ServicePoint.BindIPEndPointDelegate上的此MSDN 博客条目.它解释了如何显式创建将由HttpWebRequest使用的本地端点.

例如,要绑定到192.168.16.100:

WebRequest webReq = WebRequest.Create(myUri);
HttpWebRequest httpRequest = (HttpWebRequest)webReq;
httpRequest.ServicePoint.BindIPEndPointDelegate =
    new BindIPEndPoint(BindIPEndPointCallback);

...

private static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint,
                                                    IPEndPoint remoteEndPoint,
                                                    int retryCount)
{
    if (remoteEndPoint.AddressFamily == AddressFamily.InterNetwork)
    {
        return new IPEndPoint(IPAddress.Parse("192.168.16.100"), 0);
    }
    // Just use the default endpoint.
    return null;
}
Run Code Online (Sandbox Code Playgroud)