Creating an IPEndPoint from a hostname

后端 未结 1 1030
南方客
南方客 2021-02-13 06:58

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 ca

相关标签:
1条回答
  • 2021-02-13 07:53

    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.
    }
    
    0 讨论(0)
提交回复
热议问题