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 :

Releated Post

2 thoughts on “Getting the Client’s IP with C#

Leave a Reply

%d bloggers like this: