问题描述
我想从任何 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 吗?
解决方法
您的函数实际上只要求有线以太网 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;
}