C# - Lookup hostname

17. September 2011 10:56

 

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 hostname 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 recived in a list to make things easyier for the end user to understand. As you may get different error messages per host.

E-mail Kick it! DZone it! del.icio.us Permalink