在.NET应用程序中,如何确定使用哪个网络接口与给定的IP地址通信?
我在具有多个网络接口( IPv4和v6 )的工作站上运行,我需要获取用于与给定数据库服务器通信的“正确”接口的地址。
发布于 2009-03-07 11:13:55
最简单的方法是:
UdpClient u = new UdpClient(remoteAddress, 1);
IPAddress localAddr = ((IPEndPoint)u.Client.LocalEndPoint).Address;现在,如果您需要NetworkInterface对象,您可以执行如下操作:
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties ipProps = nic.GetIPProperties();
// check if localAddr is in ipProps.UnicastAddresses
}另一种选择是使用P/Invoke并调用GetBestInterface()。
发布于 2008-12-11 17:22:12
这两种方法实际上都不会给操作员提供他正在寻找的信息--他想知道哪个接口将用于到达给定的目的地。完成所需操作的一种方法是使用System.Diagnostics.Process类执行路由命令,然后对输出进行屏幕剪切。route PRINT (destination IP)会给你带来一些有用的东西。这可能不是最好的解决方案,但这是我现在唯一能给你的解决方案。
发布于 2008-12-11 15:02:10
您要查找的信息将在WMI中。
这个使用WMI的示例可能会让您了解大部分内容:
using System.Management;
string query = "SELECT * FROM Win32_NetworkAdapterConfiguration";
ManagementObjectSearcher moSearch = new ManagementObjectSearcher(query);
ManagementObjectCollection moCollection = moSearch.Get();// Every record in this collection is a network interface
foreach (ManagementObject mo in moCollection)
{
// Do what you need to here....
}Win32_NetworkAdapterConfiguration类将为您提供有关适配器配置的信息,例如ip地址等。
您还可以查询Win32_NetworkAdapter类以查找有关每个适配器的“静态”信息(最大速度、制造商等)。
https://stackoverflow.com/questions/359596
复制相似问题