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 ?
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.
}
You can use something like this:
var addresses = Dns.GetHostAddresses(uri);
Debug.Assert(addresses.Length > 0);
var endPoint = new IPEndPoint(addresses[0], port);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With