Determining the Active Network Interface Adapter Programmatically

The Network Interface Adapter is part of the physical system and you could find it on a Windows system by going into the control panel but what if you need to find the active NIC programmatically?

There is a function in .NET that can enumerate all of the network adapters on the system called GetAllNetworkInterfaces. Once you enumerate all of the adapters, you need to find which one is active. The following code can find the active adapter by using a UDPClient to get the local IP address and then matching it on the list of adapters.


public string ActiveNetworkInterface()
{
            string TwitterIP = "199.59.149.230";
            UdpClient u = new UdpClient(TwitterIP, 1);
            IPAddress localAddr = ((IPEndPoint)u.Client.LocalEndPoint).Address;

            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                IPInterfaceProperties ipProps = nic.GetIPProperties();
                foreach (UnicastIPAddressInformation addrinfo in ipProps.UnicastAddresses)
                {
                    if (localAddr.Equals(addrinfo.Address))
                    {
                        return nic.Description;
                    }
                }
            }
            return "Adapter not found.";
}

Thanks to the author of an answer to the following question on stackoverflow.

http://stackoverflow.com/questions/359596/identifying-active-network-interface

Advertisements
Tagged with: ,
Posted in Development

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: