0

There are many questions about how to find the local IP address, how to find the IP address for a given network interface, but I need to find the network interface to which an IP address belongs, for example to get status changes for this interface.

So, how do I get the network interface to which an given IP address is assigned to?

Hefaistos68
  • 381
  • 3
  • 9

1 Answers1

1

Using the System.Net.NetworkInformation namespace I came to the following solution:

public static NetworkInterface GetInterfaceForIP(IPAddress address)
{
    foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
    {
        foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
        {
            if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
            {
                if (address.Equals(ip.Address))
                    return ni;
            }
        }
    }

    return null;
}

Without much error checking here, this function returns the network interface for the IP.

If you need to check for status change events (cable unplugged, etc) can use the NetworkChange event in the System.Net.NetworkInformation namespace.

Geoff James
  • 3,122
  • 1
  • 17
  • 36
Hefaistos68
  • 381
  • 3
  • 9