找不到本地IP

马佐

我想从任何Windows设备获取本地IP地址。它对于我的台式PC正常工作。但是,当我尝试获取笔记本电脑或笔记本电脑的IP时,我总是会得到123.123.123.123

foreach (NetworkInterface nInterface in NetworkInterface.GetAllNetworkInterfaces()) {
    if (nInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet && nInterface.OperationalStatus == OperationalStatus.Up)
        foreach (var ip in nInterface.GetIPProperties().UnicastAddresses)
            if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                return ip.Address;
}

return IPAddress.Parse("123.123.123.123"); // Only for visualization, that none of the addresses fulfilled the conditions

我是否需要添加另一个NetworkInterfaceType?

阿农·科沃德(Anon Coward)

您的职能实际上是仅要求有线以太网IP。大多数情况下,笔记本电脑没有有线以太网地址,而是有一个带有地址的Wifi适配器。因此,您可以寻找无线IP:

foreach (NetworkInterface nInterface in NetworkInterface.GetAllNetworkInterfaces())
{
    if (nInterface.OperationalStatus == OperationalStatus.Up)
    {
        // Using a switch statement to make it a litte easier to change the logic
        switch (nInterface.NetworkInterfaceType)
        {
            case NetworkInterfaceType.Ethernet:
            case NetworkInterfaceType.Wireless80211:
                foreach (var ip in nInterface.GetIPProperties().UnicastAddresses)
                    if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                        return ip.Address;
                break;
        }
    }
}

或者,您可以改为显式忽略某些网络类型:

        // Using a switch statement to make it a litte easier to change the logic
        switch (nInterface.NetworkInterfaceType)
        {
            case NetworkInterfaceType.Loopback:
                // ignore this type
                break;
            // Anything else that's running is considered valid
            default:
                foreach (var ip in nInterface.GetIPProperties().UnicastAddresses)
                    if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                        return ip.Address;
                break;
        }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章