views:

160

answers:

3

Hi, How can I get the current visitors IP address?

+10  A: 
HttpContext.Current.Request.UserHostAddress; 
or 
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
or
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
Yongwei Xing
A: 

Request.UserHostAddress

Pavel Radzivilovsky
+9  A: 

Edit: also found an interesting question regarding IP-related http headers here.

Edit2: As mentioned in comments and in link I provided above, HTTP_X_FORWARDED_FOR header may contain multiple IP-addresses separated by comma. I didn't face this situation but suppose some corrections to my answer are required.

I use this code to get the IP address (it returns IPAddress.None value if getting failed for some reason):

    /// <summary>
    /// Gets the IP address of the request.
    /// <remarks>
    /// This method is more useful than built in because in some cases it may show real user IP address even under proxy.
    /// <summary>
    /// Gets the IP address of the request.
    /// <remarks>
    /// This method is more useful than built in because in some cases it may show real user IP address even under proxy.
    /// The <see cref="System.Net.IPAddress.None" /> value will be returned if getting is failed.
    /// </remarks>
    /// </summary>
    /// <param name="request">The HTTP request object.</param>
    /// <returns></returns>
    public static IPAddress GetIp(this HttpRequest request)
    {
        string ipString;
        if (string.IsNullOrEmpty(request.ServerVariables["HTTP_X_FORWARDED_FOR"]))
        {
            ipString = request.ServerVariables["REMOTE_ADDR"];
        }
        else
        {
            ipString = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                .FirstOrDefault();
        }

        IPAddress result;
        if (!IPAddress.TryParse(ipString, out result))
        {
            result = IPAddress.None;
        }

        return result;
    }
Alex
+1 for returning as IPAddress object
James Westgate
Be aware that the `X-Forwarded-For` header can be forged, so don't make any security decisions based on it. Only check the `HTTP_X_FORWARDED_FOR` value if the machine is behind a load balancer or reverse proxy.
devstuff
Also be aware that HTTP_X_FORWARDED_FOR will contain multiple IP-addresses if multiple proxies are passed. Does The Parse method handle this correctly?
Tomas
@Tomas: Nope, it won't work. I'll correct my answer in a few minutes. Thanks!
Alex
+1 For correctly handling multiple proxies.
Tomas