Identifying active network interface

The simplest way would be:

UdpClient u = new UdpClient(remoteAddress, 1);
IPAddress localAddr = ((IPEndPoint)u.Client.LocalEndPoint).Address;

Now, if you want the NetworkInterface object you do something like:


foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
   IPInterfaceProperties ipProps = nic.GetIPProperties();
   // check if localAddr is in ipProps.UnicastAddresses
}

Another option is to use P/Invoke and call GetBestInterface() to get the interface index, then again loop over all the network interfaces. As before, you’ll have to dig through GetIPProperties() to get to the IPv4InterfaceProperties.Index property).

Leave a Comment