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();

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s