Click here to Skip to main content
15,860,943 members
Articles / Programming Languages / C#
Article

Finding IP Address Information

Rate me:
Please Sign up or sign in to vote.
4.71/5 (47 votes)
14 Dec 20033 min read 269.2K   91   30
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:

C#
// 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.

C#
// 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.

C#
// 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


Written By
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

 
QuestionFinding IP address hardware information in C# Pin
Reza Khajepour29-Nov-14 6:53
Reza Khajepour29-Nov-14 6:53 
GeneralMy vote of 5 Pin
chandrabhanu.anand23-Mar-11 4:55
chandrabhanu.anand23-Mar-11 4:55 
GeneralKernel or in driver Pin
chandrabhanu.anand23-Mar-11 4:53
chandrabhanu.anand23-Mar-11 4:53 
GeneralMy vote of 1 Pin
zzz7net19-Jan-11 7:42
zzz7net19-Jan-11 7:42 
Questionhow to access fixed ip address computer over the internet Pin
GM-12315-Jun-09 21:11
GM-12315-Jun-09 21:11 
GeneralThe first option Pin
Jörgen Sigvardsson9-Jun-09 20:09
Jörgen Sigvardsson9-Jun-09 20:09 
Generalget ip and its location(Adress,city,country) Pin
Member 405374814-Sep-08 9:54
Member 405374814-Sep-08 9:54 
GeneralIP Pin
Member 429301924-Jun-08 21:35
Member 429301924-Jun-08 21:35 
GeneralGetting the live IP Pin
Tauhid Shaikh24-Sep-07 1:29
Tauhid Shaikh24-Sep-07 1:29 
GeneralProblem when using DHCP Pin
Yaniv Karta13-Jul-06 2:23
Yaniv Karta13-Jul-06 2:23 
Generalsame code to VB.net [modified] Pin
lvence12-Jul-06 4:48
lvence12-Jul-06 4:48 
General:You forgot another way :) Pin
Armoghan Asif17-May-05 23:43
Armoghan Asif17-May-05 23:43 
Generalgood job... Pin
Member 143348426-Apr-05 2:50
Member 143348426-Apr-05 2:50 
GeneralRe: good job... Pin
naughton9-Jun-06 12:01
naughton9-Jun-06 12:01 
Yeah, and the explanations are very good as well.
QuestionHow To Retriving IP Of Remote Machine Using WMI? Pin
shadyz14-May-04 10:24
shadyz14-May-04 10:24 
AnswerRe: How To Retriving IP Of Remote Machine Using WMI? Pin
Heath Stewart1-Jan-05 7:27
protectorHeath Stewart1-Jan-05 7:27 
GeneralIP for the Mail Exchanger Pin
Mina Gerges27-Apr-04 7:59
Mina Gerges27-Apr-04 7:59 
GeneralRe: IP for the Mail Exchanger Pin
Heath Stewart1-Jan-05 7:25
protectorHeath Stewart1-Jan-05 7:25 
GeneralUsing WMI Pin
Jim Willis27-Dec-03 8:57
Jim Willis27-Dec-03 8:57 
GeneralRe: Using WMI Pin
Bryan White28-Dec-03 7:22
Bryan White28-Dec-03 7:22 
GeneralRe: Using WMI Pin
shadyz14-May-04 10:30
shadyz14-May-04 10:30 
GeneralRemote IP not known Pin
grrrrrrr16-Dec-03 8:50
grrrrrrr16-Dec-03 8:50 
GeneralRe: Remote IP not known Pin
Daniel Grunwald23-Dec-03 23:38
Daniel Grunwald23-Dec-03 23:38 
GeneralWill not work with a router Pin
Lac15-Dec-03 18:32
Lac15-Dec-03 18:32 
GeneralRe: Will not work with a router Pin
sides_dale15-Dec-03 19:14
sides_dale15-Dec-03 19:14 

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

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