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;
            }
            else
            {
                // 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 : 
http://csharpdotnetfreak.blogspot.com/2008/12/finding-ip-address-behind-proxy-using-c.html
http://blogs.msdn.com/b/asiatech/archive/2009/08/28/how-to-obtain-ip-address-of-a-client-behind-proxy-via-web-service.aspx

Jacob Saylor

Software developer in Kentucky

2 Responses

Leave a Reply to Jacob Saylor Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: