Thursday, 18 October 2007

How do I lookup a Hostname

A colleague wanted a way to lookup a hostname through c# and all the examples he could find involved calling an API with c++.

A quick poke around the System.Net namespace found a DNS class which did everything he wanted - I wrapped it up for him to make it even easier, and here is the code I gave him:-
private void LookupAddress()
{
string strIPAddress = "192.168.1.1";
string strHostName = "";
if (TryGetHostName(strIPAddress, out strHostName))
{
MessageBox.Show(strHostName);
}
else
{
MessageBox.Show("Unable to get hostname!");
}

}
private bool TryGetHostName(string strIPAddress, out string strHostName)
{
strHostName = "";
bool blnRes = false;
try
{
System.Net.IPHostEntry oEntry = System.Net.Dns.GetHostEntry(strIPAddress);
strHostName = oEntry.HostName;
blnRes = true;
}
catch (System.Net.Sockets.SocketException err)
{
if (err.Message == "No such host is known")
{
//IP address not found error! - handle this?
}
}
catch (Exception err)
{
//Handle this type of error!
}

return blnRes;
}

Hope this helps

Ross

No comments: