C# 获取网关地址时出现NullReferenceException

C# 获取网关地址时出现NullReferenceException,c#,networking,nullreferenceexception,gateway,C#,Networking,Nullreferenceexception,Gateway,尝试访问返回值时,我被告知对象引用未设置为对象的实例,其中: return address.Address; 我从其他人的线程中提取网关IP的代码: public static IPAddress getDefaultGateway() { var card = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(); if (card == null) return null; var address =

尝试访问返回值时,我被告知对象引用未设置为对象的实例,其中:

return address.Address;
我从其他人的线程中提取网关IP的代码:

public static IPAddress getDefaultGateway()
{
    var card = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault();
    if (card == null) return null;
    var address = card.GetIPProperties().GatewayAddresses.FirstOrDefault();
    return address.Address;
}
试试这个:

public static IPAddress GetADefaultGateway()
{
    foreach (var card = NetworkInterface.GetAllNetworkInterfaces())
    {
       if (card == null)
       {
         continue;
       }

       foreach (var address = card.GetIPProperties().GatewayAddresses)
       {
         if (address == null)
         {
           continue;
         }

         //We've found one
         return address.Address;
       }
    }

    //We didn't find any
    return null;
}

检查
NetworkInterface.GetAllNetworkInterfaces()
返回的内容以及返回顺序。看起来第一个返回的接口没有定义网关地址。我只是收到“System.Net.NetworkInformation.SystemNetworkInterface[]”没有网关地址,因此
GatewayAddresses.FirstOrDefault()给你带来了很多乐趣。那么实际的代码是可靠的吗?几乎所有的
NullReferenceException
情况都是相同的。有关提示,请参阅“”。