c# - 为应用程序选择众多 Internet 连接之一

标签 c# network-programming

我的电脑有几个不同的互联网连接。局域网、无线局域网、WiFi 或 3G。所有这些都处于事件状态,机器可以使用其中的任何一个。

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

在我的 C# 应用程序中,我使用了 HttpWebRequestHttpWebResponse 类。

这可能吗?

最佳答案

这是一些高级功能,由 HttpWebRequest、WebRequest、WebClient 等抽象出来。但是,您可以使用 TcpClient(使用 constructor taking a local endpoint )或使用套接字并调用 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)到您要使用的接口(interface)的本地端点。如果您的本地计算机的 WiFi 地址的 IP 地址为 192.168.0.10,则使用该本地端点将强制套接字使用该接口(interface)。默认是未绑定(bind)的(实际上是 0.0.0.0),它告诉网络堆栈自动解析您想要规避的接口(interface)。

下面是一些基于安德鲁评论的示例代码。请注意,将 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);
        }
    }
}

关于c# - 为应用程序选择众多 Internet 连接之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4547032/

相关文章:

c++ - N*(connect + send + close) vs (Nagle disable + connect + N*send + close),N > 1

与Linux中的特定接口(interface)连接

c# - EF Core 3.1 在定义实体之间的主键关系时创建名称为 '1' 的重复列

c# - TCP 会分解小于 1kb 的数据吗?

C++ Boost Asio 简单聊天教程

linux - 我可以做些什么来减少 TCP 在 ubuntu 中的拥塞控制的影响?

c# - UDP网络与多个网络

c# - 并行运行异步方法,但确保返回有数据

c# - C# 应用程序如何轻松地在网络上通信和传输文件?

c# - 在 LINQ 查询中使用 Func<>