Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Finding IP Address Information

0.00/5 (No votes)
14 Dec 2003 1  
An article on finding IP address information

Introduction

Sometimes, it is necessary for your application to know the IP information of the machine it is running on. In a windows environment there are several ways of finding this information. This article shows three different ways to accomplish this task.

  • 1. Use DNS
  • 2. Use WMI
  • 3. Use Windows Registry

Now, let's see all these ways in more detail.

1. Use DNS

This is a fairly easy way of obtaining the IP address information. We basically make us of the Dns class contained in the C# System.Net namespace. There are several methods exposed by the Dns class which allow us to accomplish our task. Once obtaining the hostname of the local system by using GetHostName() we can call GetHostByName() to find IP address information. Below given code piece demonstrates this:

// using System.Net; 

public void UseDNS()
{
   string hostName = Dns.GetHostName();
   Console.WriteLine("Host Name = " + hostName);
   IPHostEntry local = Dns.GetHostByName(hostName);    
   foreach(IPAddress ipaddress in local.AddressList)
   {
      Console.WriteLine("IPAddress = " + ipaddress.ToString()); 
   }
}

Simple and clean. So, what is the deal with the foreach loop? Well, that is one thing you need to be careful: There is a possibility that the local system which your application is running on might have more than one IP address assigned to it. The foreach loop takes care of that. We will consider this possibility when using other approaches as well.

2. Use WMI

Now, let us see how we can use the Windows Management Instrumentation (WMI) to accomplish the same task. But before we delve into that, let's see what WMI is very shortly.

Windows 2000 and later versions of Windows OS's are equipped with a database containing information about the system -both hardware and software. There is a standard developed by Distributed Management Task Force, Inc. for accessing system information in a network environment and it is called Web-Based Enterprise Management(WBEM). WMI is basically Microsoft implementation of WBEM. If you want to use WMI and you have an earlier version of Windows OS, you can download WMI free of charge from Microsoft. For further information, you can refer to Microsoft website. WMI uses several database tables to store system related information and these tables are updated every time there is a change in the system information.

Now, let us focus on our problem. How do we use WMI to retrieve information regarding IP address of the local machine? There are several data fields we can use to query information from WMI. Important ones for our purpose would be: DNSHostName, Description, IPAddress, IPSubnet, DefaultIPGateway

Below given code shows how WMI is used to get the IP address information. It is not surprising to see a SQL statement is used to query WMI since as I mentioned earlier, we are querying a database. I used the IPEnabled field to filter network devices which don't have IP configured.

ManagementObjectSearcher class takes a sql query as an argument to its constructor and the result of the query is contained in a ManagementObjectCollection. Please note the use of foreach loop again to take into account the possibility of having multiple values for certain data fields.

// using System.Management;

public void UseWMI()
{
   string query = "SELECT * FROM Win32_NetworkAdapterConfiguration" 
        + " WHERE IPEnabled = 'TRUE'";
   ManagementObjectSearcher moSearch = new ManagementObjectSearcher(query);
   ManagementObjectCollection moCollection = moSearch.Get();
    
   // Every record in this collection is a network interface

   foreach(ManagementObject mo in moCollection)
   {
      Console.WriteLine("HostName = " + mo["DNSHostName"]);
      Console.WriteLine("Description = " + mo["Description"]);
      
      // IPAddresses, probably have more than one value

      string[] addresses = (string[])mo["IPAddress"];
      foreach(string ipaddress in addresses)
      {
         Console.WriteLine("IPAddress = " + ipaddress);
      }
      
      // IPSubnets, probably have more than one value

      string[] subnets = (string[])mo["IPSubnet"];
      foreach(string ipsubnet in subnets)
      {
         Console.WriteLine("IPSubnet = " + ipsubnet);
      }
      
      // DefaultIPGateways, probably have more than one value

      string[] defaultgateways = (string[])mo["DefaultIPGateway"];
      foreach(string defaultipgateway in defaultgateways)
      {
         Console.WriteLine("DefaultIPGateway = " + defaultipgateway);
      }
   }
}

3. Use Windows Registry

It is also possible to obtain the IP address information from the Windows Registry. Key point using the registry is to find out where in the registry the network information is stored. While Windows 98 and Me store network information on a single location for all network cards. Windows NT, 2000 and XP has a different subkey for every network card under the HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\NetworkCards

Below given code shows how to use the Registry to obtain the IP address information on Windows NT, 2000 and XP.

// using Microsoft.Win32;

public void UseRegistry()
{
   string network_card_key = "SOFTWARE\\Microsoft\\Windows NT\\" 
        + "CurrentVersion\\NetworkCards";
   string service_key = "SYSTEM\\CurrentControlSet\\Services\\";
      
   RegistryKey local_machine = Registry.LocalMachine;
   RegistryKey service_names = local_machine.OpenSubKey(network_card_key); 
   if( service_names == null )return; // Invalid Registry

   string[] network_cards = service_names.GetSubKeyNames();
   service_names.Close();
   foreach( string key_name in network_cards )
   {
      string network_card_key_name = network_card_key + "\\" + key_name;
      RegistryKey card_service_name = 
        local_machine.OpenSubKey(network_card_key_name);
      if( card_service_name == null ) return; // Invalid Registry
      
      string device_service_name = (string) card_service_name.GetValue(
          "ServiceName");
      string device_name = (string) card_service_name.GetValue(
          "Description");
      Console.WriteLine("Network Card = " + device_name);
      
      string service_name = service_key + device_service_name + 
            "\\Parameters\\Tcpip";
      RegistryKey network_key = local_machine.OpenSubKey(service_name);
      if( network_key != null )
      {
         // IPAddresses
         string[] ipaddresses = (string[]) network_key.GetValue("IPAddress");
         foreach( string ipaddress in ipaddresses ) 
         {
            Console.WriteLine("IPAddress = " + ipaddress);
         }
         
         // Subnets
         string[] subnets = (string[]) network_key.GetValue("SubnetMask");
         foreach( string subnet in subnets )
         {
            Console.WriteLine("SubnetMask = " + subnet);
         }
         
         //DefaultGateway
         string[] defaultgateways = (string[]) 
              network_key.GetValue("DefaultGateway");
         foreach( string defaultgateway in defaultgateways )
         {
            Console.WriteLine("DefaultGateway = " + defaultgateway);
         }
         network_key.Close();
      }  
   }
   local_machine.Close();
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here