Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an IPEndPoint from a hostname

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 ?

like image 634
Retrocoder Avatar asked Jan 20 '10 13:01

Retrocoder


2 Answers

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.
}
like image 156
ChaosPandion Avatar answered Nov 15 '22 01:11

ChaosPandion


You can use something like this:

var addresses = Dns.GetHostAddresses(uri);
Debug.Assert(addresses.Length > 0);
var endPoint = new IPEndPoint(addresses[0], port);
like image 38
Paulo Santos Avatar answered Nov 15 '22 02:11

Paulo Santos