代码之家  ›  专栏  ›  技术社区  ›  Retrocoder

从主机名创建ipendpoint

  •  12
  • Retrocoder  · 技术社区  · 15 年前

    我使用的是第三方DLL,它需要一个__ipendpoint__。由于用户可以输入IP地址或主机名,因此在创建IPendpoint之前,我需要将主机名转换为IP地址。在.NET中是否有任何函数可以执行此操作,或者是否必须编写自己的DNS查找代码?

    2 回复  |  直到 15 年前
        1
  •  25
  •   ChaosPandion    15 年前

    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.
    }
    
        2
  •  2
  •   Paulo Santos    15 年前

    您可以使用如下内容:

    var addresses = Dns.GetHostAddresses(uri);
    Debug.Assert(addresses.Length > 0);
    var endPoint = new IPEndPoint(addresses[0], port);