为什么我从对GetIPv4Properties的调用中获得了NullReferenceException

问题描述

注意:我知道NullReferenceException是什么以及如何调试和查找它的来源-这不是这里的问题

我的目标:对于Unity3D中的一个项目,我试图找到我所有设备的网络接口并将它们的IpAddress存储在列表中以备后用。稍后,我将在所有这些消息上广播一些消息。

除其他外,我关注了How do I get the network interface and its right IPv4 address?Broadcasting UDP message to all the available network cards(尤其是this answer),并尝试提出以下建议:

var addresses = new List<IPAddress>();

var allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

foreach (var networkInterface in allNetworkInterfaces)
{
    if (networkInterface.OperationalStatus != OperationalStatus.Up) continue;
    if (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 && networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet)continue;
    if (!networkInterface.SupportsMulticast) continue;
    if (networkInterface.Supports(NetworkInterfaceComponent.IPv4) == false) continue;

    var ipProperties = networkInterface.GetIPProperties();
    if (ipProperties == null) continue;

    var ipv4Properties = ipProperties.GetIPv4Properties(); // !! EXCEPTION IS THROWN HERE !!
    if (ipv4Properties == null) continue;

    if (NetworkInterface.LoopbackInterfaceIndex == ipv4Properties.Index) continue;
            
    var unicastAddresses = ipProperties.UnicastAddresses;

    foreach (var unicastIpAddressinformation in unicastAddresses)
    {
        if (unicastIpAddressinformation.Address.AddressFamily != AddressFamily.InterNetwork) continue;

        addresses.Add(unicastIpAddressinformation.Address);
    }
}

// and yes I used Linq before but I converted it to the loop due to debug the exception ^^

例外

System.NullReferenceException:对象引用未设置为对象的实例
位于(包装由本机托管)System.Net.networkinformation.Win32IPv4InterfaceProperties.GetPerAdapterInfo(int,System.Net.networkinformation.Win32_IP_PER_ADAPTER_INFO,int&)
at System.Net.networkinformation.Win32IPv4InterfaceProperties..ctor(System.Net.networkinformation.Win32_IP_ADAPTER_ADDRESSES addr,System.Net.networkinformation.Win32_MIB_IFROW mib)[0x00030]在中
在System.Net.networkinformation.Win32IPInterfaceProperties2.GetIPv4Properties()[0x00000]在:0中
在C:\ xxxxxx \ broadcast.cs:797中的broadcast.broadCastTest(System.UInt16 broadcastPort,System.Net.sockets.UdpClient客户端)[0x000ae]

被扔进去

var ipv4Properties = ipProperties.GetIPv4Properties();

其中ipProperties不是 null,因此显然它来自GetIPv4Properties内部的某个地方。 API中列出的唯一可能引发的异常是networkinformationException,而不是NullReferenceException

也是在我检查并确认之前

networkInterface.Supports(NetworkInterfaceComponent.IPv4)

true(这是我的以太网接口,因此显然是IPv4接口)。

那为什么会引发异常,我该如何解决呢?

我在做蠢事吗? ^^


更新

遵循原理,通过注释掉它来解决它,我现在只是跳过loopBack检查

// var ipv4Properties = ipProperties.GetIPv4Properties();
// if (ipv4Properties == null) continue;

// if (NetworkInterface.LoopbackInterfaceIndex == ipv4Properties.Index) continue;

自从afaik以来,回环应该已经被覆盖

networkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)