Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 找不到本地IP_C#_System.net - Fatal编程技术网

C# 找不到本地IP

C# 找不到本地IP,c#,system.net,C#,System.net,我想从任何Windows设备获取本地IP地址。它适用于我的台式电脑。但当我尝试获取笔记本电脑的IP或我的surface时,我总是得到123.123.123 foreach (NetworkInterface nInterface in NetworkInterface.GetAllNetworkInterfaces()) { if (nInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet && nI

我想从任何Windows设备获取本地IP地址。它适用于我的台式电脑。但当我尝试获取笔记本电脑的IP或我的surface时,我总是得到
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.GetAllNetworkInterfaces()中的NetworkInterface nInterface)
{
if(nInterface.OperationalStatus==OperationalStatus.Up)
{
//使用switch语句使更改逻辑更加容易
交换机(nInterface.NetworkInterfaceType)
{
案例NetworkInterfaceType.Ethernet:
案例NetworkInterfaceType.Wireless8021:
foreach(nInterface.GetIPProperties().unicastaddress中的var ip)
if(ip.Address.AddressFamily==AddressFamily.InterNetwork)
返回ip地址;
打破
}
}
}
或者,您可以显式忽略某些网络类型:

//使用switch语句使更改逻辑更加容易
交换机(nInterface.NetworkInterfaceType)
{
案例NetworkInterfaceType.环回:
//忽略此类型
打破
//正在运行的任何其他内容都被认为是有效的
违约:
foreach(nInterface.GetIPProperties().unicastaddress中的var ip)
if(ip.Address.AddressFamily==AddressFamily.InterNetwork)
返回ip地址;
打破
}

看起来与此问题类似。。。我将检查并查看批准的答案是否解决了您的问题。我已经使用DNS尝试过了。同样的问题我注意到这段代码只处理IPv4