A short guide on how to lookup a host name in c# and return an ip address. The first thing you will probably notice is that you may get more than one host name because of how dns looks. If you are writing a program using them you should start by using the first one returned and if it does not work try the others on the list.

Sounds complex? Well its not really. The following code does the lookup. Where Hostname is a string.

IPAddress[] Addr = Dns.GetHostAddresses(HostName);

Just after making this call it is a good idea to check if the addr contains zero items. As it is valid for the call to return zero addresses but still success because the host name is valid with a different record type. eg an MX record for mail servers but does not have an A record. It may also throw an exception on failure.

You can then loop over the Addr attempting to connect to the correct service. I am assuming here that your connect method would throw an exception if it was unable to connect to the service correctly.

bool Connected = false;
Exception LastEx = null;
for (int i = 0; i < Addr.Length; i++)
{
        try
        {
                MyClass.Connect(Addr[0]);
                Connected = true;
                break;
        }
        catch (Exception ex)
        {
                LastEx = ex;
        }
}

if (Connected == false)
{
        ShowErrorToUser(LastEx);
        return;
}

You may also want to show all the exception messages received in a list to make
things easier for the end user to understand. As you may get different error
messages per host.



Did You find this page useful?

Yes No



Last Modified: 21 February 2017

Releated Posts


2011-10-27 - CSharp - Number Of Cores and Processors
2011-10-04 - CSharp - Thread Queue Example
2011-09-29 - CSharp - Background Thread / Task
2011-09-17 - CSharp - Lookup Hostname
2011-08-29 - CSharp - IsGuid
2011-08-29 - C Sharp - StopWatch, The high resolution timer
2011-08-26 - CSharp - Convert Between Meters and Feet
2011-08-23 - CSharp - ThreadPool and Windows Forms
2011-08-10 - C Sharp - MD5Sum / SHASum
2011-07-22 - CSharp - Fibonacci sum
2011-07-13 - CSharp - Palindrome
2011-07-11 - CSharp - The string Reverse
2011-07-10 - CSharp - Interviews FizzBuzz
2011-06-27 - CSharp - HowTo Parse a URL
2011-06-22 - CSharp - Extending any class
2011-06-13 - ASPNET - Login by username or email
2011-05-12 - CSharp - ASPNET Logoff
2011-03-07 - C Sharp - Windows Logoff
2011-03-02 - ASPNET - Dynamic Controls
2011-03-01 - C Sharp - Resize an image by size of height
2011-02-23 - C Sharp / MSSQL Get inserted value of NEWSEQUENTIALID()
2011-02-10 - CSharp - Wake on Lan (WOL) Packet
2011-02-10 - CSharp - Shutdown or reboot windows
2011-02-06 - C Sharp - Gridview Bound Yes No
2011-02-05 - MSSQL - Levenshtein
2011-01-30 - MSSQL - Enabling CLR Functions
2011-01-30 - MSSQL - Adding MD5 checksum support
2011-01-30 - MSSQL - RegEx Support
2011-01-30 - MSSQL - Adding SHASum support