14.2. Converting a Hostname to an IP Address
Problem
You have a string representation of a host (such as oreilly.com), and you need to obtain the IP address from this hostname.
Solution
Use the Dns.GetHostEntry method to get the IP addresses. In the following code, a hostname is provided to the GetHostEntry method, which returns an IPHostEntry from which a string of addresses can be constructed. If the hostname does not resolve, a SocketException stating "No such host is known" is thrown:
using System;
using System.Net;
using System.Text;
public static string HostNameToIP(string hostName)
{
IPHostEntry iphost = System.Net.Dns.GetHostEntry(hostName);
IPAddress[] addresses = iphost.AddressList;
StringBuilder addressList = new StringBuilder( );
foreach(IPAddress address in addresses)
{
addressList.AppendFormat("IP Address: {0};", address.ToString( ));
}
return addressList.ToString( );
}
// Writes "IP Address: 208.201.239.37;IP Address: 208.201.239.36;"
Console.WriteLine(HostName2IP("www.oreilly.com"));Discussion
An IPHostEntry can associate multiple IP addresses with a single hostname via the AddressList property. AddressList is an array of IPAddress objects, each of which holds a single IP address. Once the IPHostEntry is resolved, the AddressList can be looped over using foreach to create a string that shows all of the IP addresses for the given hostname. If the entry cannot be resolved, a SocketException is thrown.
See Also
The "DNS Class," "IPHostEntry Class," and "IPAddress" topics ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access