Wednesday, 16 January 2013

Get a user's client IP address in ASP.NET?

We have Request.UserHostAddress to get the IP address in ASP.NET, but this is usually the user's ISP's IP address, not exactly the user's machine IP address who for example clicked a link. How can I get the real IP Address?


Often you will want to know the IP address of someone visiting your website. While ASP.NET has several ways to do this one of the best ways we've seen is by using the "HTTP_X_FORWARDED_FOR" of the ServerVariables collection.
Here's why...
Sometimes your visitors are behind either a proxy server or a router and the standardRequest.UserHostAddress() only captures the IP address of the proxy server or router. When this is the case the user's IP address is then stored in the server variable ("HTTP_X_FORWARDED_FOR").
So what we want to do is first check "HTTP_X_FORWARDED_FOR" and if that is empty we then simply return ServerVariables("REMOTE_ADDR").
While this method is not foolproof, it can lead to better results. Below is the ASP.NET code in C#:
using System;
using System.Net;
 
public class IPNetworking
{
  public static string GetIP4Address()
  {
    string IP4Address = String.Empty;
 
    foreach (IPAddress IPA in Dns.GetHostAddresses(Request.ServerVariables["REMOTE_ADDR"].ToString())))
    {
      if (IPA.AddressFamily.ToString() == "InterNetwork")
      {
        IP4Address = IPA.ToString();
        break;
      }
    }
 
    if (IP4Address != String.Empty)
    {
      return IP4Address;
    }
 
    foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
    {
      if (IPA.AddressFamily.ToString() == "InterNetwork")
      {
        IP4Address = IPA.ToString();
        break;
      }
    }
 
    return IP4Address;
  }
}

0 comments:

Post a Comment

 

Copyright @ 2013 PakTechClub.