在.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。
Here, server is hardcoded to an IP address, but in my application it could potentially be something like "server.test".
将我的项目转换为.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回答了这里:
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)问题
发布评论