从主机名创建IPEndPoint

Ret*_*der 13 c# network-programming

我正在使用需要"IPEndPoint"的第三方DLL.由于用户可以输入IP地址或主机名,因此我需要先将主机名转换为IP地址,然后才能创建IPEndPoint.是否有任何功能在.net中执行此操作,或者我将不得不编写自己的DNS查找代码?

Cha*_*ion 26

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.
}
Run Code Online (Sandbox Code Playgroud)

  • 它应该是列表中的第一个ip,因为每次期望客户端使用第一个时,循环DNS服务器将以不同的顺序提供它,因此使用列表中的第一个;). (7认同)
  • 你怎么知道`addresses [0]`是返回地址列表中最合适的地址? (2认同)