Monday, October 4, 2010

Get IP Address by Host Name

Webpages can be called in the browser by entering easy to remember addresses. That we do not have to remember the cryptical IP addresses of the server hosting the pages is due to the DNS (Domain Name System) service.
This maps in requests URLs to IP Addresses, which are then actually called.
To use C# to get the IP addresses behind the host names, we can use the class Dns from System.Net.
The function GetHostByName() returns an array of IP addresses, which are deposited for the given host.
The following code returns the IP address of the server, on which this blog is hosted (using System.Net is required):

foreach (IPAddress IP in Dns.GetHostByName("csharp-tricks.blogspot.com").AddressList)
{
    Console.WriteLine(IP.ToString());
}

No comments:

Post a Comment