How to check for loopback IP address on Windows 7

Transition from Windows XP to Windows 7 has been raising new issues every day during development of desktop as well as web applications. Most of these are not issues per se. They are changes that were introduced during Windows Vista and are part of Windows 7 as well. This piece of information has to do with network protocols on Windows 7. Here is what happened. I am developing a web application. One of the things I had to do in the application is to check if the request URL is from localhost or loopback address then do something different otherwise follow normal routine. So I was comparing Request.UserHostAddress with standard loopback address of 127.0.0.1. It was working fine. Then I started an instance of IE and tried to test the page. Well, nothing seemed to work. When I debugged the code, I saw that value of Request.UserHostAddress was ::1 instead of 127.0.0.1. By looking at the IP address I could tell that it was standard IPv6 loop back IP address. Actually the loopback address on an IPv6 network is 0:0:0:0:0:0:0:1 which is abbreviated as ::1. Then I paid close attention to IPAddress class in .Net framework. There is a method IsLoopback that you can use to test for loopback address. And you will use Parse method to create instance of IPAddress object. After making these changes, my implementation looked as below.


private void GetUserFromIp()
{
 UserGeoLocator geoLocator = new UserGeoLocator();
 _userLocation = null;
 var ip = IPAddress.Parse(Request.UserHostAddress);
 if (IPAddress.IsLoopback(ip) ||
  string.Compare(Request.UserHostAddress, "127.0.0.1", 0) == 0)
 {
  _userLocation = geoLocator.GetUserLocationByIp("68.xxx.xxx.xxx");
 }
 else
 {
  _userLocation = geoLocator.GetUserLocationByIp(Request.UserHostAddress);
 }
}

IPv6 is enabled by default on Windows Vista as well as Windows 7. If you use Visual Studio Development Server to debug your application, you will notice that loopback address is in IPv4 format but if you use IIS to debug your ASP.Net application, the loopback address is in IPv6 format. To avoid any issues like this, using IsLoopback makes the implementation neutral to format because framework will take care of interpretting the IP address correctly when you use Parse to create instance of IPAddress object.

You can diable use of IPv6 on Windows 7 by following instructions in How to disable certain Internet Protocol version 6 (IPv6) components in Windows Vista, Windows 7 and Windows Server 2008. If you are not using any format specific implementation, then you do not have to do that and I would not suggest doing it if you are not comfortable dealing with changing registry entries.

comments powered by Disqus

Search

Social

Weather

7.2 °C / 45.0 °F

weather conditions Clouds

Monthly Posts

Blog Tags