Get IP Address from Domain Name and Vice versa using .NET

Let us see how to get an IP address of a domain. We will also see how to get a DNS name if we supply the IP address. The comments marked in the code will help you understand what’s going on. The domain name used here is just for demonstration purpose. Please do not abuse by firing multiple requests. Replace the domain name and IP address with one that belongs to you.

Create a console app and add a reference to System.Net and System.Net.Sockets. Declare a Main method that looks similar to the one shown below:

get ip address

Now let us add the GetIpAddress() and GetDomainName() static methods:

// Get Ip Address from DomainName
static void GetIPAddress(string hostname)
{
IPAddress[] ipAddr = Dns.GetHostAddresses(hostname);
Console.WriteLine("GetHostAddresses({0}) :", hostname);

foreach (IPAddress ip in ipAddr)
{
Console.WriteLine(ip);
}
}

// Get HostName from IPAddress
static void GetDomainName(string ipaddress)
{
IPHostEntry hostEntry = Dns.GetHostEntry(ipaddress);
Console.WriteLine("DNS name : " + hostEntry.HostName);

//Aliases if any
String[] aliases = hostEntry.Aliases;
for (int i = 0; i < aliases.Length; i++)
{
Console.WriteLine("Alias: " + aliases[i]);
}
}

The Dns.GetHostAddresses method returns the Internet Protocol (IP) addresses for the specified host. Similarly Dns.GetHostEntry method resolves a host name or IP address to an IPHostEntry instance. When an IPHostEntry instance is returned, it has the properties set – like the AddressList, Aliases, and HostName. In the example shown above, we are accessing the HostName property

get host entry

OUTPUT

get host address

Note: Reverse DNS or looking up for a DomainName given an IPAddress may not always fetch the results you expect. The process of reverse resolving an IP address uses the Pointer DNS record type (PTR record). However in cases of a web farm, the hostnames are very generic. Sometimes the PTR record does not even exist. It is also possible that a stale DNS record for an IPv4 address belonging to a different host can be returned. Read more here

In case of IPv6, most IPv6 do not register the PTR record for an IPv6 address.






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

3 comments:

eCommerce said...

Does this help to get IP addresses of the sites owned by others. Let me copy this code.

Unknown said...

Thanks

Unknown said...

Thanks