Latest Post

Saturday, 10 September 2016

Get User IP Address using the ASP.Net C#

 Hello everyone, I am sharing  the code for end user machine using the ASP.Net C#.

public static string GetUserIPAddress()
{

  var request = System.Web.HttpContext.Current.Request;
  var ServerVariables_HTTP_X_FORWARDED_FOR =  (String)request.ServerVariables["HTTP_X_FORWARDED_FOR"];

 var ServerVariables_REMOTE_ADDR = (String)request.ServerVariables["REMOTE_ADDR"];
 var ServerVariables_UserHostAddress = HttpContext.Current.Request.UserHostAddress;
 var ServerVariables_HTTP_CLIENT_IP = (String)request.ServerVariables["HTTP_CLIENT_IP"];

 String ip = "";

 if (!string.IsNullOrEmpty(ServerVariables_HTTP_X_FORWARDED_FOR) &&  !ServerVariables_HTTP_X_FORWARDED_FOR.ToLower().Contains("unknown"))
  {
    ServerVariables_HTTP_X_FORWARDED_FOR = ServerVariables_HTTP_X_FORWARDED_FOR.Trim();
    string[] ipRange = ServerVariables_HTTP_X_FORWARDED_FOR.Split(',');
    ip = ipRange[0];
  }
  else if (!string.IsNullOrEmpty(ServerVariables_REMOTE_ADDR))
  {
    ServerVariables_REMOTE_ADDR = ServerVariables_REMOTE_ADDR.Trim();
    ip = ServerVariables_REMOTE_ADDR;
  }

  if (string.IsNullOrEmpty(ip))
  {
    if (!string.IsNullOrEmpty(ServerVariables_UserHostAddress))
    {
      ip = ServerVariables_UserHostAddress;
    }
    else if (!string.IsNullOrEmpty(ServerVariables_HTTP_CLIENT_IP))
    {
     ip = ServerVariables_HTTP_CLIENT_IP;
    }
  }

  if (!string.IsNullOrEmpty(ip)) 
  {
     if (ip.LastIndexOf(":") > 0) 
     {
          ip = ip.Substring(0, ip.LastIndexOf(":"));
     }
   }

 return ip;
}

Government Jobs