识别特定的网络适配器

时间:2013-07-10 15:32:15

标签: c# .net networking network-programming ip

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

我需要在我的应用程序中使用特定适配器的ip地址,麻烦的是我不知道有关该适配器的足够信息。 适配器的名称不是常量,它们之间的网络屏蔽或它们连接的顺序(即索引)也不是。

我也不能依赖使用适配器的ping地址,因为我说它们连接到不同的网络(因此可以从多个网络中删除特定的地址),并且因为并非所有适配器都必须连接到网络所有的时间。

我对适配器的了解是:

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

是否有其他信息\技术\ dark-voodoo我可以用来识别特定的适配器?

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

1 个答案:

答案 0 :(得分:0)

您需要使用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;
    }