How to Retrieve "Network Interfaces" in C#

Environment: C# .NET

The following code is used to retrieve the "network interfaces" in C#. You may recognize the "network interfaces" as "Network and Dial-up Connections": You can access them by using "Start > Setting > Network and Dial-up Connections". C# does not provide a simple way of retrieving this list. The solution includes two main steps, which follow:

Step 1: Retrieve the Network Adapters

Get all the Network Adapters, which are IP-enabled, and their Setting ID. We use the ManagementClass: Win32_NetworkAdapterConfiguration to achieve this. The "SettingID" property of the ManagementObject is actually the Registry key.

Step 2: Extract information from the Registry

According the "SettingID", extract the following value from the Registry:

   HKEY_LOCAL_MACHINE\
      SYSTEM\CurrentControlSet\control\Network\{xxxxxx}\
             <SettingID>\connection

Where {xxxxxx} is an unknown value, there for we go over all the keys under SYSTEM\CurrentControlSet\control\Network\ and <SettingID> is the values we found in Step 1.

using Microsoft.Win32;
using System.Management;

// holds the network interfaces names (such as "Local Area
// Connection")
private string[] networkInterfaces = new string[MAX_CONNECTIONS];

// holds the network interface Registry key (which is the SettingID
// of the adapter, such as: B76D5407-4610-499A-A8A5-50AAD2A2297E)
private string[] networkInterfacesSettingId =
                 new string[MAX_CONNECTIONS];

// holds the number of network interfaces found
private int numberOfNetworkInterfaces = 0;

// extract all the IP-enabled adapters and get their SettingID
// (which is the Registry key)
ManagementClass objMC = new ManagementClass(
                        "Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();

foreach(ManagementObject objMO in objMOC)
{
   if( Convert.ToBoolean(objMO["ipEnabled"]) == false )
      continue;

   string SettingID = "";
   try
   {
      networkInterfacesSettingId[numberOfNetworkInterfaces] =
          (string)objMO["SettingID"];
      ++numberOfNetworkInterfaces;
   }
   catch{}
}

if(numberOfNetworkInterfaces == 0)
{
   MessageBox.Show("No Network Interface were found on this local
                    machine", "Error", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
   return;
}

int j=0;

// The network interfaces are in the following path in the Registry:
// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\control\
//      Network\{xxxxxx}\SettingID\connection

RegistryKey networkRegistry = currentMachineRegistry.OpenSubKey(
            "SYSTEM\\CurrentControlSet\\control\\Network");
int num = networkRegistry.SubKeyCount;
string[] tmp = networkRegistry.GetSubKeyNames();
for(int i=0; i<num; ++i)
{
   // get all the {xxxxxx} keys under 'Network'
   RegistryKey conReg = networkRegistry.OpenSubKey(tmp[i]);
   if(conReg != null)
   {
      string[] tmp1 = conReg.GetSubKeyNames();
      if(tmp1.Length > 0)
      {
         for(int k=0; k<tmp1.Length; ++k)
         {
            // get all the <SettingID> keys under 'Network\{xxxxxx}'
            RegistryKey reg = conReg.OpenSubKey(tmp1[k]);
            if(reg != null)
            {
               int gg = Array.BinarySearch(
                        networkInterfacesSettingId, 0, 
                        numberOfNetworkInterfaces, tmp1[k]);
               if(gg >= 0)
               {
                  // This subkey was found in the
                  // networkInterfacesSettingId array - which means
                  // that this is a valid network interface -
                  // let's get the interface name
                  // get the 'connection' key under
                  // 'Network\{xxxxxx}\<SettingID>'
                  RegistryKey r = reg.OpenSubKey("connection");
                  if(r != null)
                  {
                     Object obj = r.GetValue("Name");
                     networkInterfaces[gg] = obj.ToString();
                  }
               }
            }
         }
      }
   }
}

Downloads

Download source - 4 Kb


Comments

  • An Easier Way?

    Posted by nathon on 09/08/2010 11:23am

    I just wanted to propose possibly an easier way of getting at this information. Using the .NET Framework you can retrieve an array of System.Net.NetworkInformation.NetworkInterface objects by simply calling the following method. System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); Doing so also allows you to get at other information that's built into the API, such as .GetIsNetworkAvailable, which returns boolean indicating whether that particular interface is up. This is also very handy for doing things like populating a dropdownlist with all network interfaces.

    Reply
  • Don't use the registry

    Posted by Lochkarte on 05/06/2009 08:05am

    You should use Win32_NetworkAdapter to retrieve that information. Win32_NetworkAdapterConfiguration.SettingID is the same value as Win32_NetworkAdapter.GUID And Win32_NetworkAdapter.NetConnectionID is what you are looking for.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds