识别特定的网络适配器

本文关键字:网络适配器 识别 | 更新日期: 2023-09-27 18:22:00

我的应用程序在具有多个网络适配器(2-4个)的计算机上运行,所有适配器都连接到不同的内部网络。

我需要获得一个特定适配器的ip地址,以便在我的应用程序中使用,问题是我对该适配器的信息了解不够。适配器的名称不是恒定的,它们之间的网络屏蔽或它们的连接顺序(即索引)也不是恒定的。

我也不能依赖于使用适配器来ping地址,因为正如我所说,它们连接到不同的网络(因此可以从多个网络中抓取特定地址),并且因为并非所有适配器都必须始终连接到网络。

我对适配器的了解是:

  • 所有适配器的IP地址都是静态的(当然,应用程序和许多机器之间的IP地址不同)
  • 我需要的适配器是计算机板载适配器

有没有其他信息''技术''黑暗巫毒我可以用来识别特定的适配器?

我的应用程序在C#-.Net 4中运行,但由于这一点非常关键,我会使用应用程序中的所有CLI、包装或脚本语言来解决此问题。

识别特定的网络适配器

您需要使用pInvoke GetBestInterface(),然后找到具有该索引的接口,并获取他的IpAddress。

[System.Runtime.InteropServices.DllImport("iphlpapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        public static extern int GetBestInterface(UInt32 DestAddr, out UInt32 BestIfIndex);
    private string GetCorrectIPAddress(string server_ip_string)
    {
        string correctIpAddress = "";
        System.Net.IPAddress server_IpAddress = System.Net.Dns.GetHostEntry("server_ip_string").AddressList[0];
        UInt32 ipv4AddressAsUInt32 = BitConverter.ToUInt32(server_IpAddress.GetAddressBytes(), 0);
        UInt32 interfaceindex;
        int result = GetBestInterface(ipv4AddressAsUInt32, out interfaceindex);
        foreach (System.Net.NetworkInformation.NetworkInterface nic in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
        {
            System.Net.NetworkInformation.IPInterfaceProperties ipProps = nic.GetIPProperties();
            if (ipProps.GetIPv4Properties().Index == interfaceindex)
            {
                correctIpAddress = ipProps.UnicastAddresses[0].Address.ToString();
            }
        }
        return correctIpAddress;
    }