识别活动网络接口

在.NET应用程序中,如何识别用于与给定IP地址通信的网络接口?

我在具有多个网络接口,IPv4和v6的工作站上运行,我需要获取用于流量到我给定数据库服务器的“正确”接口的地址。

最简单的方法是:

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()来获取接口索引,然后再次遍历所有网络接口。 和以前一样,你必须通过GetIPProperties()来挖掘IPv4InterfaceProperties.Index属性。

这些都不会给OP提供他正在寻找的信息 – 他想知道哪个接口将用于到达给定目的地。 执行所需操作的一种方法是使用System.Diagnostics.Process类转发到route命令,然后屏幕截取输出。 route PRINT (destination IP)将为您提供可用的东西。 这可能不是最好的解决方案,但它是我现在唯一可以给你的解决方案。

您所需的信息将在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类,找出每个适配器的“静态”(最大速度,制造商等)

只是为了给出一个完整的图片:另一种方法是使用Socket.IOControl( SIO_ROUTING_INTERFACE_QUERY, ... )

ConferenceXP包含相当全面的function包装,适用于IPv4 / 6和多播地址: https : //github.com/conferencexp/conferencexp/blob/master/MSR.LST.Net.Rtp/NetworkingBasics/u力.cs#L84

至少你可以从那开始,为你提供本地机器的dns的所有地址。

 IPHostEntry hostEntry = Dns.GetHostEntry(Environment.MachineName); foreach (System.Net.IPAddress address in hostEntry.AddressList) { Console.WriteLine(address); }