Geekpedia Programming Tutorials






Get the IP of a host

Getting the IP address and host name of a host / webhost using System.Net.

On Tuesday, June 15th 2004 at 11:14 AM
By Andrew Pociu (View Profile)
*****   (Rated 4.5 with 11 votes)
Contextual Ads
More C# Resources
Advertisement
The following code asks you for a host and then returns the IP address of that host. The code is self-explanatory thanks to the comments.





using System;

// using the System.Net namespace

using System.Net;

class Class1

{

[STAThread]

static void Main(string[] args)

{

// Request the name

Console.Write("Please type the name of the host: ");

// Store it in 'host'

string host = Console.ReadLine();

try

{

// Get the DNS information

IPHostEntry ipHost = Dns.GetHostByName(host);

// Display the host name

Console.WriteLine("Host name: {0}", ipHost.HostName);

// Store the list of IP adresses

IPAddress[] ipAddr = ipHost.AddressList;

// Loop to actually display the IP

for(int x = 0; x < ipAddr.Length; x++)

{

Console.WriteLine("IP address: {0}", ipAddr[x].ToString());

}

}

// Catch the exception (if host was not found)

catch(System.Net.Sockets.SocketException)

{

Console.WriteLine("Host not found.");

}

}

}



Here is an example result:





Please type the name of the host: www.geekpedia.com

Host name: geekpedia.com

IP address: 65.75.151.74

Press any key to continue



Also if you want to return the hostname of an IP use Dns.Resolve() instead of Dns.GetHostByName.
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Andy Jump on Thursday, July 8th 2004 at 05:06 AM

ther reverse can be done very easily too by just exchanging the

Dns.GetHostByName(host);

for

Dns.GetHostByAddress(IP);

this will only work if the dns entry has a reverse lookup though.

by ali on Monday, April 18th 2005 at 06:01 PM

i want information about code get ip header in c#

by Attila Turóczy on Saturday, July 22nd 2006 at 12:36 AM

Perfect tutorial!!

by herumi on Thursday, December 13th 2007 at 05:28 AM

Why the application close automatically before I see the result???
Thanks for share this tutorial???

by on Thursday, January 3rd 2008 at 01:43 PM

"Why the application close automatically before I see the result???
Thanks for share this tutorial???"

Because it has finished it's job. Add Console.Readline after "try".

by Rosen Rusev on Tuesday, January 8th 2008 at 11:10 AM

Simple but effective!


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons