为什么dns.gethotentry()方法返回addresslist为空?

本文关键字:返回 addresslist 为空 方法 dns gethotentry 为什么 | 更新日期: 2023-09-27 18:05:19

我使用以下代码来获取IP地址:

var ip =  Dns.GetHostEntry(host);                     
var ipaddress = ip.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString();

我可以从命令提示符ping这个主机名。

但是当我使用GethostEntry()时,它会正确返回主机名。

,但AddressList为空。

它也不工作,而我给本地机器的ipaddress。
为什么会这样?

为什么dns.gethotentry()方法返回addresslist为空?

尝试使用下面的代码:

PHostEntry host;
 string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
  foreach (IPAddress ip in host.AddressList)
{
 if (ip.AddressFamily == AddressFamily.InterNetwork)
 {
    localIP = ip.ToString();
   }
}
 return localIP;