Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with System.Net.Dns.GetHostEntry(dnsServer) on .NET 4.0

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

like image 509
Jason Kealey Avatar asked Apr 26 '10 14:04

Jason Kealey


People also ask

What is DNS GetHostEntry?

GetHostEntry(IPAddress) Resolves an IP address to an IPHostEntry instance. GetHostEntry(String) Resolves a host name or IP address to an IPHostEntry instance.

What is System Net DNS?

The Dns class is a static class that retrieves information about a specific host from the Internet Domain Name System (DNS).


1 Answers

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

like image 66
Jeremy Bull Avatar answered Oct 25 '22 12:10

Jeremy Bull