簡體   English   中英

識別特定的網絡適配器

[英]Identifying a specific network adapter

我的應用程序在具有多個網絡適配器(在2-4之間)的計算機上運行,​​所有計算機都連接到不同的內部網絡。

我需要獲取特定適配器的ip地址以在我的應用程序中使用,麻煩是我不了解有關該適配器的足夠信息。 適配器的名稱不是恆定的,適配器之間的網絡掩碼也不是它們的連接順序(即索引)。

我也不能依靠使用適配器來ping地址,因為正如我說的那樣,它們連接到不同的網絡(因此可以從多個網絡中竊取特定的地址),並且因為並非所有適配器都必須始終都連接到網絡。

我對適配器的了解是這樣的:

  • 所有適配器的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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM