locked
Sample code RRS feed

  • Question

  • User364663285 posted

    Hi,

    Is there any sample code for the way to capture current IP of client machine, within Code behind?

    Monday, April 30, 2018 6:57 AM

All replies

  • User283571144 posted

    Hi wmec,

    As far as I know, if the IP Address is determined for the Client machine’s which are behind Routers or Proxy Servers , we could check HTTP_X_FORWARDED_FOR server variable in the request to get the client IP address

    But, if  the client is not using any Proxy Server, we should check REMOTE_ADDR server variable in the request to get the client IP address.

    More details, you could refer to below codes:

    string ipaddress;
    ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (ipaddress == "" || ipaddress == null)
        ipaddress = Request.ServerVariables["REMOTE_ADDR"];

    Best Regards,

    Brando

    Tuesday, May 1, 2018 5:25 AM
  • User-386954757 posted
      public static string GetIPAddress(HttpContextBase httpContext, HttpRequestBase webContext)
            {
                try
                {
                    if (httpContext != null)
                    {
                        return httpContext.Request.UserHostAddress != null ? httpContext.Request.UserHostAddress.ToString() : string.Empty;
                    }
                    else
                    {
                        return webContext.UserHostAddress != null ? webContext.UserHostAddress.ToString() : string.Empty;
                    }
                }
                catch (Exception)
                {
                    return string.Empty;
                }
            }

    Tuesday, May 1, 2018 6:17 AM