c#获取所有网络接口的IP地址,每个适配器获取多个ipv4地址

时间:2017-08-17 22:01:32

标签: c# networking ipv6 ipv4

在我的应用程序中,我需要显示每个可用(wifi或以太网)适配器的IP地址。

问题是我每个适配器获得的IP地址超过一个,并且我得到的最后一个(每个适配器)是我正在寻找的。

我不知道前两个(通常是前两个)ip地址是什么,以及如何获得“真正的”ip地址。我比较了这两个ip地址,我得到的是“真正的”之前用cmd和“ipconfig”命令并没有在那里提到它们,因此它不是默认网关,子网掩码,本地Ipv6或公共IP地址。

This是我的应用输出的内容,this就是我想要的。

我使用的代码:

foreach (NetworkInterface inf in devs)
        {
            if (inf.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || inf.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
            {
                foreach (UnicastIPAddressInformation address in inf.GetIPProperties().UnicastAddresses)
                {
                    if (address.Address.AddressFamily == AddressFamily.InterNetwork)
                        MessageBox.Show(address.Address.ToString());
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

以下是如何获取每个适配器的IP地址(IPv4和IPv6)的答案。

NetworkInterface[] intf = NetworkInterface.GetAllNetworkInterfaces();
foreach(NetworkInterface device in intf)
{
    IPAddress ipv6Address = device.GetIPProperties().UnicastAddresses[0].Address;   //This will give ipv6 address of certain adapter
    IPAaddress ipv4Address = device.GetIPProperties().UnicastAddresses[1].Address;//This will give ipv4 address of certain adapter
}
相关问题