How to get active network interface in c#
Replies: 0   Views: 7301  Subscribers: 0

Posted by Justin · 12-05-2012 - 00:00

Edited by reece · 12-11-2012 - 04:44
Figured some people might find this useful. Iv'e been searching around in the .NET framework for potential ways to get the active network interface being used for outgoing traffic on a given computer. My solution I resulted with is to use Windows Management Instrumentation(WMI) to automatically get the MAC address associated with the active network interface. Then use the System.Net.NetworkInformation classes to enumerate through all the network interfaces until matching the the MAC address found in WMI with the the MAC address of the given interface. Here is the code:
­Get Active MAC Address using WMI­
static string GetMacAddress()
            //Get list of all Win32_NetworkAdapter objects.
            ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection collection = searcher.Get();
            //Iterate through results until the property 'MacAddress' is found.
            foreach (ManagementObject obj in collection)
                if (obj.Properties["MacAddress"] != null)
                        string value = obj.Properties["MacAddress"].Value.ToString();
                        return value;
                    catch (NullReferenceException) { }

            return "";
­Compare WMI MAC address with the collection of MAC addresses from the Network Interfaces­ ­[CODE="C#"]string wmiMacAddress = ""; string networkInterfaceName = ""; wmiMacAddress = GetMacAddress(); //Get collection of all network interfaces on the given machine. NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); for (int i = 0 ; i < nics.Length; i++) { //Compare the network interface's MAC address with the one found using WMI //and append upon succesion. if (nics­[i].GetPhysicalAddress().ToString() == wmiMacAddress.Replace(":", "")) { networkInterfaceName = nics­[i].Description; } } Console.WriteLine("Active Network Interface: {0}", networkInterfaceName); ­[/CODE] As you can see pretty straight forward. Hope some people find this useful. ­[:SMILE:]­