20

How can I get the current visitors IP address?

Oleks
  • 31,955
  • 11
  • 77
  • 132
Lennie De Villiers
  • 5,119
  • 7
  • 31
  • 30

5 Answers5

25

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;
    }
Community
  • 1
  • 1
Oleks
  • 31,955
  • 11
  • 77
  • 132
  • 4
    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 Apr 12 '10 at 09:45
  • 2
    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 Apr 12 '10 at 10:42
  • @Tomas: Nope, it won't work. I'll correct my answer in a few minutes. Thanks! – Oleks Apr 12 '10 at 10:56
  • Now I'm like almost one year after, but is it guaranteed that this will return the client IP? Let say a proxy forge the `X-Forwarded-For` and then the proxy has it is own mapping, that way the client IP is not reaching the host. Am I right? Also, are you sure the first IP is the original... what I mean is, it is defined that proxies and load balancers append instead of prepend to the list of IPs – Tomas Jansson Feb 08 '11 at 13:23
  • @Tomas Jansson: when dealing with the IP addresses in this way you cannot be sure the given IP address is valid. I assume, that at least half of them are real IP addresses(not forged), but unfortunatelly I don't have any stats on this. So my answers to your questions are: nope; yep; nope. – Oleks Feb 08 '11 at 15:29
  • 2
    In case anyone is wondering (like I was), the first IP in the HTTP_X_FORWARDED_FOR list is the originating IP (so this example is correct, at least according to wikipedia). That said, if you are doing this for logging purposes, I would suggested simply logging the entire REMOTE_ADDR and HTTP_X_FORWARDED_FOR headers. Let humans decide what information is useful in the case of attacks. – Jordan Morris May 27 '13 at 06:56
20

HttpContext.Current.Request.UserHostAddress;

or

HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

or

HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

Code Guru
  • 393
  • 5
  • 15
Yongwei Xing
  • 12,983
  • 24
  • 70
  • 90
2

Request.UserHostAddress

Pavel Radzivilovsky
  • 18,794
  • 5
  • 57
  • 67
1
public String GetIP()
{
    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();
    }
    return ipString;
}

First trying to find out proxy IP,if its null we can get that system IP

Syed Mohamed
  • 1,339
  • 1
  • 15
  • 23
0

Try this to get external ip address of user..

public static string getExternalIp()
    {
        try
        {

            string externalIP;
            externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
            externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                         .Matches(externalIP)[0].ToString();
            return externalIP;
        }
        catch { return null; }
    }
Imran Athar
  • 469
  • 5
  • 8