【问题标题】:Identifying a specific network adapter识别特定的网络适配器
【发布时间】:2013-07-08 15:09:39
【问题描述】:

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

我需要获取特定适配器的 IP 地址以在我的应用程序中使用,问题是我不知道有关该适配器的足够信息。 适配器的名称不是恒定的,它们之间的网络掩码或它们的连接顺序(即索引)也不是恒定的。

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

我对适配器的了解如下:

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

我可以使用任何其他信息\技术\dark-voodoo 来识别特定适配器吗?

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

【问题讨论】:

  • 在设备管理器网络适配中有一个位置。不确定 0 是否总是意味着 on-board。而且我不知道如何在 .NET 中获取这些信息。
  • 我试图走这条路,但据我了解,板载适配器的 0 索引取决于使用的主板类型。和我的问题中的许多其他因素一样,它不是恒定的。

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


【解决方案1】:

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

【讨论】:

  • 从我读过的内容中,GetBestInterface 检索与给定地址具有最佳连接的接口(我猜是您的建议中的 server_ip_string)。这不好,因为不同的接口连接到不同的网络。每个给定的 IP 地址都可以映射到每个不同网络上的不同机器,因此所有接口都可能与给定地址有很好的连接,但它们是不同的机器。顺便说一句,不要花太多时间在这上面,它已经三年了,而且系统已经更换了。
猜你喜欢
  • 1970-01-01
  • 2015-05-30
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多