我有一个C#Win 7桌面应用程序,该应用程序使用HttpClient发送Web请求。有没有办法找出哪个网络适配器或NetworkInterface用于发送这些请求?(可能有多个LAN,WAN和虚拟适配器。)
我真的不想使用TcpClient,UdpClient或任何套接字级别的程序,因为它的级别更低,用户可能决定阻止端口。
我尝试采用的一种方法是找到当前请求的IP地址,然后尝试将其与NetworkInterface的IP地址进行匹配(使用NetworkInterface.GetAllNetworkInterfaces),但是HttpClient不会告诉您用于发送的IP请求。
这就是我最终要做的事情:
IPAddress localAddr = null;
try
{
using (UdpClient udpClient = new UdpClient("8.8.8.8", 0)) //connect to google dns
{
localAddr = ((IPEndPoint)udpClient.Client.LocalEndPoint).Address;
udpClient.Client.Close();
udpClient.Close();
}
}
catch (SocketException sex)
{
Console.WriteLine("Failed to make UDP connection, no connection to DNS ? ");
}
//find all network interfaces
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
NetworkInterface activeAdapter = null;
foreach (NetworkInterface adapter in nics.Where(n => n.OperationalStatus == OperationalStatus.Up))
{
//wifi adapter will be 'up' only if its associated with a hotspot
IPInterfaceProperties properties = adapter.GetIPProperties();
var match = properties.UnicastAddresses.Any(a => a.Address.Equals(localAddr));
if (match)
{
activeAdapter = adapter;
break;
}
}
我不得不依靠UDP客户端,找不到从HttpClient获取IP的方法
这将为您提供用于连接到Internet的当前“活动”网络适配器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句