Follow us

Tuesday, October 19, 2010

How to get host name and associated IP Addresses of a machine?

Introduction

The DNS class in the System.Net namespace can be used to get the host name of a machine or get the IP address if the host name is already known.

The DNS class is a static class that provides access to information from the Internet Domain Name System (DNS). The information returned includes multiple IP addresses and aliases if the host specified has more than one entry in the DNS database. The list is returned as a collection or an array of  IPAddress objects.

Code

Include the Namespace

using System.Net;

Refer the following c# code

//  First get the host name of local machine.
string hostName = Dns.GetHostName();

//  Then using host name, get the IP address list associated 
//  with host name
IPAddress[] addresses = Dns.GetHostAddresses(hostName);
        
for (int i = 0; i < addresses.Length; i++)
{
  Response.Write("IP Address " + (i + 1) + " :: " + addresses[i].ToString() + "<br>");
}

Note:

If your machine is in LAN then,above code will not give you the IP Address assigned by the ISP. The code for getting the real IP assigned by ISP is as follows:
//  Get the IP Address assigned by ISP
string userIPAddress = Request.UserHostAddress.ToString();

Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

0 comments: on "How to get host name and associated IP Addresses of a machine?"

Post a Comment