Get the IP of a host

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

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



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();



// 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)



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




Here is an example result:

Please type the name of the host:

Host name:

IP address:

Press any key to continue

Also if you want to return the hostname of an IP use Dns.Resolve() instead of Dns.GetHostByName.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top