C#: Resolve a Host Name to an IP Address.

Problem:
You want to determine the IP address for a compter based on its fully qualified domain name by performing a DNS query.
 
Solution:
In .NET Framework 2.0, use the method GetHostEntry of the System.Net.Dns.Class, and pass the computer’s fully qualified domain name as a string parameter.
(In version 1.0 and 1.1 of the .NET Framework, you should use the method GetHostByName of the DNS class, but it’s marked as obsolete in 2.0.)

 using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (string comp in args)
            {
                try
                {
                    IPAddress[] addresses = Dns.GetHostEntry(comp).AddressList;
                    foreach (IPAddress address in addresses)
                    {
                        Console.WriteLine("{0} = {1} ({2})", comp, address, address.AddressFamily);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("{0} = Error ({1})", comp, ex.Message);
                }
            }
            Console.WriteLine("Press Enter…");
            Console.ReadLine();
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s