.NET 4.0 上的 System.Net.Dns.GetHostEntry(dnsServer) 问题

发布于 2024-08-29 23:00:24 字数 917 浏览 12 评论 0原文

我已经在 .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 地址解析主机名,则会抛出异常)。

I have been using the following code for months (without problem) in a .NET 2.0/3.5 environment:

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);

Here, server is hardcoded to an IP address, but in my application it could potentially be something like "server.test.com".

When converting my project to .NET 4.0, this code stopped working when directly passing an IP address (still works with a hostname). It crashes with this exception:

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)

Because all I need is the resulting IPEndPoint, I can work around the issue by using IPAddress.Parse to generate the IPAddress object, but I want to know if any of you know why this behaviour changed in .NET 4.0? (If we can't resolve the hostname from the IP address, an exception is now thrown).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梨涡少年 2024-09-05 23:00:24

微软回答了这个 此处

故意将其更改为更多
一致地表示名称解析
失败。如果你有输入字符串
你只想转换成
IP地址,建议
您使用 IPAddress.TryParse 或
Dns.GetHostAddresses

Microsoft answered this here:

this was purposely changed to more
consistently represent name resolution
failures. If you have input strings
that you just want to convert to
IPAddresses, it is recommended that
you use IPAddress.TryParse or
Dns.GetHostAddresses

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文