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

8Mar/132

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

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:
    http://mycodepad.wordpress.com/2013/04/26/c-getting-a-user-ip-behind-a-proxy-http_x_forwarded_for/


Leave a Reply

No trackbacks yet.

%d bloggers like this: