Click here to Skip to main content
Click here to Skip to main content

Finding IP Address Information

, 14 Dec 2003
Rate this:
Please Sign up or sign in to vote.
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

Share

About the Author

Coskun Oba
President OBACS Corporation
Canada Canada
Founder of OBACS Corporation, Coskun Oba holds a Master’s of Science degree in Nuclear Astrophysics from Colorado School of Mines, Golden, Colorado USA. Over the last fifteen years he held various positions in some of the most prestigious high tech companies around the world to develop state of the art software applications in industries, such as GIS, Telecommunication, Voice recognition and Scientific Computing.

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberchandrabhanu.anand23-Mar-11 4:55 
GeneralKernel or in driver Pinmemberchandrabhanu.anand23-Mar-11 4:53 
GeneralMy vote of 1 Pinmemberzzz7net19-Jan-11 7:42 
Questionhow to access fixed ip address computer over the internet PinmemberIftikhar Ali15-Jun-09 21:11 
GeneralThe first option PinmemberJörgen Sigvardsson9-Jun-09 20:09 
Generalget ip and its location(Adress,city,country) PinmemberMember 405374814-Sep-08 9:54 
GeneralIP PinmemberMember 429301924-Jun-08 21:35 
GeneralGetting the live IP PinmemberTauhid Shaikh24-Sep-07 1:29 
GeneralProblem when using DHCP PinmemberYaniv Karta13-Jul-06 2:23 
Generalsame code to VB.net [modified] Pinmemberlvence12-Jul-06 4:48 
General:You forgot another way :) PinmemberArmoghan Asif17-May-05 23:43 
Generalgood job... PinmemberAwsok26-Apr-05 2:50 
GeneralRe: good job... Pinmembernaughton9-Jun-06 12:01 
QuestionHow To Retriving IP Of Remote Machine Using WMI? Pinmembershadyz14-May-04 10:24 
AnswerRe: How To Retriving IP Of Remote Machine Using WMI? PinprotectorHeath Stewart1-Jan-05 7:27 
GeneralIP for the Mail Exchanger PinmemberMina Gerges27-Apr-04 7:59 
GeneralRe: IP for the Mail Exchanger PinprotectorHeath Stewart1-Jan-05 7:25 
GeneralUsing WMI PinmemberJim Willis27-Dec-03 8:57 
GeneralRe: Using WMI PinmemberBryan White28-Dec-03 7:22 
GeneralRe: Using WMI Pinmembershadyz14-May-04 10:30 
GeneralRemote IP not known Pinmembergrrrrrrr16-Dec-03 8:50 
GeneralRe: Remote IP not known Pinmemberynik23-Dec-03 23:38 
GeneralWill not work with a router PinmemberLac15-Dec-03 18:32 
GeneralRe: Will not work with a router Pinmembersides_dale15-Dec-03 19:14 
GeneralRe: Will not work with a router PinmemberLuckySmoke23-Mar-07 7:31 
AnswerRe: Will not work with a router Pinmembersides_dale23-Mar-07 17:20 
GeneralRe: Will not work with a router PinmemberLuckySmoke24-Mar-07 6:42 
AnswerRe: Will not work with a router Pinmembersides_dale24-Mar-07 15:49 
AnswerRe: Will not work with a router Pinmembersides_dale24-Mar-07 17:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140821.2 | Last Updated 15 Dec 2003
Article Copyright 2003 by Coskun Oba
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid