Tech Talk A software developer on all things tech, and then some


Getting the Client’s IP with C#

I needed a pretty reliable and easy way to get the client's IP address in one of the applications I'm working on. Granted the IP is just used for log purposes, I still wanted to pull from the request vs using some JS. There are multiple ways to do this, some work in some situations, some work in others, etc... So I decided to write a method that would work through the most reliable, then work my way down.

private string GetClientIPAddress()
            if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                // Let's first check for a proxy
                var ipAddresses = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(',');
                return ipAddresses[0].Trim();
            else if (System.Web.HttpContext.Current.Request.UserHostAddress != null
                && System.Web.HttpContext.Current.Request.UserHostAddress != string.Empty)
                // If they are not using one
                return System.Web.HttpContext.Current.Request.UserHostAddress;
                // And the hail mary jic
                return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

While this won't be the answer 100% of the time, it should be good for most. Hope this helps and happy coding!

The code was made with help from the folling sources :

Tagged as: , Leave a comment
Comments (2) Trackbacks (0)
  1. HTTP_X_FORWARDED_FOR can return multiple IPs, so your code will fail some times.

    Read this, if you want:

Leave a Reply

No trackbacks yet.

%d bloggers like this: