本文介绍了从主机名创建IPEndPoint的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

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 can create an IPEndPoint. Is there any functions to do this in .net or am I going to have to write my own DNS lookup code ?

推荐答案

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.
}

这篇关于从主机名创建IPEndPoint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-09 03:06