.NET 4.0上的System.Net.Dns.GetHostEntry(dnsServer)问题 [英] Problem with System.Net.Dns.GetHostEntry(dnsServer) on .NET 4.0

查看:444
本文介绍了.NET 4.0上的System.Net.Dns.GetHostEntry(dnsServer)问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET 2.0 / 3.5环境中,我几个月来一直在使用以下代码(没有问题):

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

在这里,服务器被硬编码为IP地址,但是在我的应用程序中它可能像是 server.test.com。

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

将我的项目转换为.NET 4.0时,直接传递IP地址时此代码停止工作(仍然可以使用主机名)。发生以下异常而崩溃:

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)

因为我需要的只是生成的IPEndPoint,所以我可以通过使用IPAddress.Parse生成IPAddress对象来解决此问题,但是我想知道你们中是否有人知道为什么此行为在.NET 4.0中发生了变化? (如果无法从IP地址解析主机名,则会引发异常。)

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

推荐答案

Microsoft回答了< a href = http://connect.microsoft.com/VisualStudio/feedback/details/561083/dns-gethostentry-behaves-differently-in-net-4-0-than-previous-versions rel = noreferrer>这里:

Microsoft answered this here:


故意将其更改为更多
,始终代表名称解析
失败。如果输入的字符串
只想转换为
IPAddresses,建议
使用IPAddress.TryParse或
Dns.GetHostAddresses

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

这篇关于.NET 4.0上的System.Net.Dns.GetHostEntry(dnsServer)问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆