1

When trying to access the returned value I'm told that the object reference is not set to the instance of the object where:

return address.Address;

The code that I used from someone else's thread to extract the gateway IP:

public static IPAddress getDefaultGateway()
{
    var card = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault();
    if (card == null) return null;
    var address = card.GetIPProperties().GatewayAddresses.FirstOrDefault();
    return address.Address;
}
Kara
  • 6,115
  • 16
  • 50
  • 57
Jake
  • 915
  • 1
  • 7
  • 22
  • 1
    Check what is returned by `NetworkInterface.GetAllNetworkInterfaces()` and in which order it is returned. It looks like the first returned interface has no gateway address defined. – Reda Nov 24 '13 at 17:13
  • I just receive "System.Net.NetworkInformation.SystemNetworkInterface[]" – Jake Nov 24 '13 at 17:32
  • There are no gateway addresses so `GatewayAddresses.FirstOrDefault();` is giving you null – Alberto Nov 24 '13 at 17:35
  • Hmm, interesting. So the actual code is sound? – Jake Nov 24 '13 at 17:47
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Nov 24 '13 at 18:11

1 Answers1

0

Try this:

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;
}
Reda
  • 2,289
  • 17
  • 19