从主机名创建IPEndPoint

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

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

你可以使用这样的东西:

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