gpt4 book ai didi

c# - 从主机名创建 IPEndPoint

转载 作者:可可西里 更新时间:2023-11-01 08:03:39 28 4
gpt4 key购买 nike

我正在使用需要“IPEndPoint”的第三方 dll。由于用户可以输入 IP 地址或主机名,因此我需要先将主机名转换为 IP 地址,然后才能创建 IPEndPoint。在 .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.
}

关于c# - 从主机名创建 IPEndPoint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2101777/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com