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.
Collapse

// 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.
Collapse

// 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();
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值