gpt4 book ai didi

c# - 限制 webclient 使用 wifi 或以太网,反之亦然

转载 作者:太空宇宙 更新时间:2023-11-03 10:25:30 25 4
gpt4 key购买 nike

我已经连接到 wifi,而且我可以通过以太网访问互联网。有没有办法控制 WebClient.DownloadString 使用以太网而不是 wifi 或 wifi 而不是以太网?

最佳答案

这是一些高级功能,由 HttpWebRequest、WebRequest、WebClient 等抽象出来。但是,您可以使用 TcpClient(使用 constructor taking a local endpoint)或使用套接字并调用 Socket.Bind 来执行此操作。

如果需要使用特定的本地端点,请使用 Bind 方法。您必须先调用 Bind,然后才能调用 Listen 方法。除非需要使用特定的本地端点,否则在使用 Connect 方法之前不需要调用 Bind。绑定(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# - 限制 webclient 使用 wifi 或以太网,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31721137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com