views:

369

answers:

1

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

A: 

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