大佬教程收集整理的这篇文章主要介绍了未找到本地 IP,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想从任何 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;
}
以上是大佬教程为你收集整理的未找到本地 IP全部内容,希望文章能够帮你解决未找到本地 IP所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。