【问题标题】:No local IP found未找到本地 IP
【发布时间】:2021-03-01 19:51:20
【问题描述】:

我想从任何 Windows 设备获取本地 IP 地址。它适用于我的台式电脑。但是当我尝试获取笔记本电脑或 Surface 的 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 吗?

【问题讨论】:

标签: c# system.net


【解决方案1】:

您的函数实际上只要求有线以太网 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;
        }

【讨论】:

    猜你喜欢
    • 2015-06-22
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 2016-09-10
    • 1970-01-01
    相关资源
    最近更新 更多