代码之家  ›  专栏  ›  技术社区  ›  Tiberiu Ana

识别主动网络接口

  •  25
  • Tiberiu Ana  · 技术社区  · 17 年前

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

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

    5 回复  |  直到 12 年前
        1
  •  38
  •   Yariv    16 年前

    最简单的方法是:

    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
    }
    


    GetBestInterface() 要获取接口索引,请再次循环所有网络接口。和以前一样,你得挖过去 GetIPProperties() 到达 IPv4InterfaceProperties.Index 财产)。

        2
  •  5
  •   Coderer    17 年前

    这两种方法实际上都不会给OP提供他想要的信息——他想知道哪个接口将用于到达给定的目的地。做你想做的事情的一种方法是向 路线 route PRINT (destination IP) 会给你一些有用的东西。这可能不是问题所在 最好的

        3
  •  3
  •   Paul Nearney    17 年前

    您要查找的信息将位于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

    您还可以查询 Win32_NetworkAdapter 类以了解每个适配器的“静态”(最大速度、制造商等)

        4
  •  2
  •   Kevin Vaughan    17 年前

    至少你可以从这个开始,给你本地机器的所有dns地址。

    IPHostEntry hostEntry = Dns.GetHostEntry(Environment.MachineName);
    
    foreach (System.Net.IPAddress address in hostEntry.AddressList)
    {
        Console.WriteLine(address);
    }
    
        5
  •  2
  •   lxa    12 年前

    让我们完整地了解一下:另一种方法是使用 Socket.IOControl( SIO_ROUTING_INTERFACE_QUERY, ... )

    ConferenceXP包含相当全面的功能,可用于IPv4/6和多播地址: https://github.com/conferencexp/conferencexp/blob/master/MSR.LST.Net.Rtp/NetworkingBasics/utility.cs#L84

    推荐文章