You have a string representation of a host (such as www.funcode.org), and you need to obtain the IP address from this hostname. The System.Net.Dns class is provided for simple DNS resolution functionality. The Resolve method returns an IPHostEntry from which a string of addresses can be constructed and returned.

In the following code, a hostname is passed resolved, and the IP addresses (if more than one) are printed to the console:

using System;
using System.Net;
using System.Text;

// ...

public static string HostName2IP(string hostname)
{
    // resolve the hostname into an iphost entry using the dns class
    IPHostEntry iphost = System.Net.Dns.Resolve(hostname);
    // get all of the possible IP addresses for this hostname
    IPAddress[] addresses = iphost.AddressList;
    // make a text representation of the list
    StringBuilder addressList = new StringBuilder();
    // get each ip address
    foreach (IPAddress address in addresses)
    {
        // append it to the list
        addressList.Append("IP Address: ");
        addressList.Append(address.ToString());
        addressList.Append(";");
    }
    return addressList.ToString();
}

// ...

// writes IP address of www.funcode.org
Console.WriteLine(HostName2IP("www.funcode.org"));

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.

Popularity: 2% [?]