我正在使用需要“IPEndPoint”的第三方dll。由于用户可以输入IP地址或主机名,因此在创建IPEndPoint之前,需要将主机名转换为IP地址。 .net中有任何功能可以执行此操作,还是我必须编写自己的DNS查找代码?
最佳答案
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.
}
关于c# - 从主机名创建IPEndPoint,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2101777/