In my previous article, How to track visitors to your site in ASP.NET & C#, I discussed how you can log the Host Info for each page visitor on your site using Dns.GetHostByAddress function.
One thing I did not stress out was the need to catch all exceptions from that method call. There are cases when this call:
string
ipAddress = Dns.GetHostByAddress(ipAddress).HostName;
Will not succeed, and you will get the following Exception:
Server Error in '/' Application.
The requested name is valid, but no data of the requested type was found
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.Sockets.SocketException: The requested name is valid, but no data of the requested type was found
Source Error:
Line 21: // Track Visitors Line 22: string ipAddress = IpAddress(); Line 23: string hostName = Dns.GetHostByAddress(ipAddress).HostName; |
From what I gathered, this happens with users connect from machines that are not listed on the Active Directory, or if their network settings is not "use NETBIOS over TCPIP". In all cases, not catching the exception on your side can mean your site is not going to work for these users.
To avoid this, I modified the code as follows:
try
{
hostName = Dns.GetHostByAddress(ipAddress).HostName;
}
catch (Exception ex)
{
Logger.EmailError(ex);
hostName += ex.Message;
}
This will let your site surfer in even if we can't resolve their machine host name.
Putting the above code, I got so many cases with users visiting my site generating this error, well at least now they can get in, where before, the web app would crash.
Thanks to my good friend John Sonmez who pointed out the error :)
Happy Programming!