本文介绍了选择许多互联网连接中的一个用于应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些不同的互联网连接的计算机。 LAN,WLAN,WiFi或3G。所有这些都是积极的,机器可以使用其中任何一个。

I have a computer with a few different internet connections. LAN, WLAN, WiFi or 3G. All of these are active and the machine can use any of them.

现在我想告诉我的应用程序使用的可用连接之一。例如,我想告诉我的应用程序只使用无线网络,而其他的软件可以使用别的东西。

Now I want to tell my application to use one of the available connections. For example I want to tell my application to use only WiFi while other software might use something else.

在我的C#应用​​程序,我用类,如的HttpWebRequest HttpWebResponse

In my c# application I use classes like HttpWebRequest and HttpWebResponse.

这甚至可能吗?

推荐答案

这是由两个HttpWebRequest的,WebRequest的,Web客户端之类的抽象出来有些高级功能。你可以,但是,的TcpClient (使用的),或使用套接字并调用Socket.Bind.

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.

如果你需要使用一个特定的本地端点使用绑定的方法。你必须调用bind之前,你可以调用Listen方法。你不需要使用Connect方法,除非你需要使用一个特定的本地端点之前调用bind。

绑定到本地端点要使用的接口。如果你的本地计算机拥有了WiFi地址的IP地址为192.168.0.10,然后使用一个本地端点将迫使套接字使用该接口。默认为未绑定(真0.0.0.0)告诉网络协议栈自动解决接口,要规避。

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.

下面是根据安德鲁的评论的一些例子code。注意,指定0作为本地端点端口意味着它是动态的。

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

这篇关于选择许多互联网连接中的一个用于应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:01
查看更多