Getting IP address given the host name



You have developed the next big socket application. But your users are not sure about the IP address of the server they want to connect to. They input host name most of the time and you require IP addresses for your code to work well. No problemo… Use the following function to get the IP address of a host, given its name:

using System.Net;
public string GetIPAddress(string sHostName)
{
IPHostEntry ipEntry = Dns.GetHostByName(sHostName);
IPAddress [] addr = ipEntry.AddressList;
string sIPAddress = addr[0].ToString();
return sIPAddress;
}

To get the IP of the local machine, use the following method before invoking GetIPAddress():

string sHostName = Dns.GetHostName();