Thursday, November 10, 2011

Replacing GetHostByName with GetHostAddresses

I’m working on some C# code that needs to send some data over a socket connection.  The user can specify the destination by name or by IP address.  I was using syntax like the following to get the address

IPAddress addr = Dns.GetHostByName(host).AddressList[0];

IPEndPoint endPoint = new IPEndPoint(addr, 9100);

That worked, but VS2010 spits out the following warning:

'System.Net.Dns.GetHostByName(string)' is obsolete: '"GetHostByName is obsoleted for this type, please use GetHostEntry instead."'   

So I replaced the call to GetHostByName with GetHostEntry. When I passed in the IP address as a string GetHostByName, it threw an error, "No such host is known".

That's not good. I didn't want to use obsolete code, but the recommended replacement wasn't working. I did a bit of searchnng on the Internets and found that GetHostEntry attempts to do a DNS reverse resolve and that doesn't always work. As it turns out, GetHostEntry is not the only method that can be substituted for GetHostByName. GetHostAddresses will return the IP address for the specified host. I was able to use the following code without any warnings:

IPAddress addr = Dns.GetHostAddresses(host)[0];

IPEndPoint endPoint = new IPEndPoint(addr, 9100);

And we are good.


  1. I don't know much about .NET, but I love how in C, you can use getaddrinfo(), which is so much more convenient than the old system of shifting bit endianness, using memcpy() to put strings into bit fields, etc. Are you opposed to using native calls that are less arbitrarily changed than the .NET equivalents?

  2. Thanks! That was very helpful.


Note: Only a member of this blog may post a comment.