在.NET 4.0中使用System.Net.Dns.GetHostEntry(dnsServer)存在问题

9

在.NET 2.0/3.5环境中,我已经使用以下代码数月(没有问题):

string server="192.168.1.3";
IPHostEntry ipe = System.Net.Dns.GetHostEntry(server);
IPAddress ipa = ipe.AddressList[0];
IPEndPoint ipep = new IPEndPoint(ipa, (int)UdpServices.Domain);

这里,服务器的IP地址是硬编码的,但在我的应用程序中,它可能是类似"server.test.com"的东西。

当将我的项目转换为.NET 4.0时,直接传递IP地址的代码停止工作(使用主机名仍然有效)。它会崩溃并出现以下异常:

System.Net.Sockets.SocketException was unhandled
  Message=The requested name is valid, but no data of the requested type was found
  Source=System
  ErrorCode=11004
  NativeErrorCode=11004
  StackTrace:
       at System.Net.Dns.InternalGetHostByAddress(IPAddress address, Boolean includeIPv6)
       at System.Net.Dns.GetHostEntry(String hostNameOrAddress)

因为我只需要得到结果的IPEndPoint,所以我可以通过使用IPAddress.Parse生成IPAddress对象来解决此问题,但我想知道为什么在.NET 4.0中更改了这种行为?(如果我们无法从IP地址解析主机名,现在会抛出异常)。

1个回答

7
微软在这里回答了这个问题:链接
引用:
这是故意更改的,以更一致地表示名称解析失败。如果您有要转换为IP地址的输入字符串,建议使用IPAddress.TryParse或Dns.GetHostAddresses。

这个链接有效: https://connect.microsoft.com/VisualStudio/feedback/details/561083/dns-gethostentry-behaves-differently-in-net-4-0-than-previous-versions - empty

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接