Creating an IPEndPoint from a hostname

后端 未结 1 828
故里飘歌
故里飘歌 2021-02-13 07:23

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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-13 08:00

    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)
提交回复
热议问题