Saturday, November 5, 2011

How to display IPAddress of hosts using c#

This sample program demonstrates the use of the Dns, IPAddress, and IPHostEntry classes. The program takes a list of names or IP addresses as command-line parameters and prints the name and an IP address of the local host, followed by the names and IP addresses of the hosts specified on the command line.
The Dns class has several methods for resolving IP addresses. The GetHostName() method takes no arguments and returns a string containing the local host name. The GetHostByName() and Resolve() methods are basically identical; they take a string argument containing the host name to be looked up and returns the IP address and host name information for the supplied input in the form of an IPHostEntry class instance. The GetHostByAddress() method takes a string argument containing the dotted-quad string representation of an IP address and also returns host information in an IPHostEntry instance.

using System; // For String and Console
using System.Net; // For Dns, IPHostEntry, IPAddress
using System.Net.Sockets; // For SocketException
class IPAddressExample {
static void PrintHostInfo(String host) {
try {
IPHostEntry hostInfo;
// Attempt to resolve DNS for given host or address
hostInfo = Dns.Resolve(host);
// Display the primary host name
Console.WriteLine("\tCanonical Name: " + hostInfo.HostName);
// Display list of IP addresses for this host
Console.Write("\tIP Addresses: ");
foreach (IPAddress ipaddr in hostInfo.AddressList) {
Console.Write(ipaddr.ToString() + " ");
// Display list of alias names for this host
Console.Write("\tAliases: ");
foreach (String alias in hostInfo.Aliases) {
Console.Write(alias + " ");
} catch (Exception) {
Console.WriteLine("\tUnable to resolve host: " + host + "\n");
static void Main(string[] args) {
// Get and print local host info
try {
Console.WriteLine("Local Host:");
String localHostName = Dns.GetHostName();
Console.WriteLine("\tHost Name: " + localHostName);
} catch (Exception) {
Console.WriteLine("Unable to resolve local host\n");
// Get and print info for hosts given on command line
foreach (String arg in args) {
Console.WriteLine(arg + ":");

1 comment:

  1. This is one of the best articles I read online. No crap, just useful information. Very well presented. Thanks for sharing with us. Here I also want to share a nice post which i have found over internet related to this post. please check out this link....

    Thanks Again !! Everyone