views:

87

answers:

2

I am using a third-party dll that requires an “IPEndPoint”. As the user can enter either an IP Address or a Host name, I need to convert a Host name to an IP address before I can create an IPEndPoint. Is there any functions to do this in .net or am I going to have to write my own DNS lookup code ?

+2  A: 

System.Net.Dns.GetHostAddresses

public static IPEndPoint GetIPEndPointFromHostName(string hostName, int port, bool throwIfMoreThanOneIP)
{
    var addresses = System.Net.Dns.GetHostAddresses(hostName);
    if (addresses.Length == 0)
    {
        throw new ArgumentException(
            "Unable to retrieve address from specified host name.", 
            "hostName"
        );
    }
    else if (throwIfMoreThanOneIP && addresses.Length > 1)
    {
        throw new ArgumentException(
            "There is more that one IP address to the specified host.", 
            "hostName"
        );
    }
    return new IPEndPoint(addresses[0], port); // Port gets validated here.
}
ChaosPandion
How do you know `addresses[0]` is the most suitable address in the list of returned addresses?
dtb
You don't know but the odds are very slim that it matters.
ChaosPandion
A: 

You can use something like this:

var addresses = Dns.GetHostAddresses(uri);
Debug.Assert(addresses.Length > 0);
var endPoint = new IPEndPoint(addresses[0], port);
Paulo Santos