C#获取所有本地IP地址

时间:2014-07-13 10:07:50

标签: c# ip

我正在使用此代码从所有界面中查找所有IP地址:

foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{    
    if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
    {
        foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
        {
            if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                ...
            }
        }
    }
}

问题是在某些电脑上它显示了ip 169.254.x.x(我知道这是“默认”的ip地址..这里没用。)

如果我ipconfig /all我没有看到这个ip,但真正的问题是我怎样才能避免显示这个ip?

1 个答案:

答案 0 :(得分:3)

在这种情况下,使用IsDnsEligible来消除自动IP地址似乎很合适;

foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
    if(!ip.IsDnsEligible)
        continue;

    if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
    {
    ...