我正在使用需要“IPEndPoint”的第三方dll。由于用户可以输入IP地址或主机名,因此我需要先将主机名转换为IP地址,然后才能创建IPEndPoint。是否有任何功能在.net中执行此操作,或者我将不得不编写自己的DNS查找代码?
答案 0 :(得分:25)
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.
}
答案 1 :(得分:2)
您可以使用以下内容:
var addresses = Dns.GetHostAddresses(uri);
Debug.Assert(addresses.Length > 0);
var endPoint = new IPEndPoint(addresses[0], port);