Wednesday, February 5, 2014

[C#] Upgrade Dns.Resolve to Dns.GetHostEntry

I am using .NET Framework 4.5 develop TCP socket program, when I try MSDN "Asynchronous Server Socket Example", VS2013 said "Resolve is obsoleted for this type, please use GetHostEntry instead." on here:
socket01

According Obsolete Members in the .NET Framework 4.5, I replace Dns.Resolve method with Dns.GetHostEntry, run the Socket Server Example, then I got some exception.

That was due to the example code get IPAddress using "ipHostInfo.AddressList[0]", normally we start the TCP server on IPv4, and the old method Dns.Resolve return IPv4 address at first of array, so using "ipHostInfo.AddressList[0]" to get IPAddress will work, but Dns.GetHostEntry will return IPv6 address, so we need to pickup the IPv4 address up.

//older way
//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
//IPAddress ipAddress = ipHostInfo.AddressList[0];

//.net 4.5
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList.First(x => x.AddressFamily == AddressFamily.InterNetwork);

So it will get first IPv4 address, the code was working in my case, hope it's working on your case too.

No comments:

Post a Comment