获取网关地址时出现NullReferenceException

时间:2013-11-24 17:08:45

标签: c# networking nullreferenceexception gateway

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

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;
}

1 个答案:

答案 0 :(得分:0)

试试这个:

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;
}