c# - 未找到本地 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;
}
推荐阅读
- wordpress - 在functions.php中错误WordPress测试Phpunit调用函数
- azure-active-directory - 配置前端以使用 B2C 进行身份验证(在 NuxtJS 中)
- excel - 使用maatwebsite在laravel中导入excel文件时如何设置实时进度条?
- c# - SendGrid 问题 "{"errors":[{"message":"Maximum credits exceeded","field":null,"help":null}]}"
- html - 带有中间图像缩放的推荐旋转木马
- php - 我们如何使用数组访问对象?
- text - 如果数据框中的字符串包含子字符串,则将所有内容替换为其他内容
- javascript - Angular/typescript 映射对象
- python - 在python中将带有图像的目录转换为csv文件
- javascript - Adobe Forms - 用户添加新字段的能力