Sirwan Afifi
Sirwan Afifi

Reputation: 10824

How to get local IP address behind the proxy

I am using this extension method to track the user's IP address:

public static string GetUser_IP_Address(string input = null)
{
    string visitorsIpAddr = string.Empty;
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
    {
         visitorsIpAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else if (!string.IsNullOrEmpty(HttpContext.Current.Request.UserHostAddress))
    {
         visitorsIpAddr = HttpContext.Current.Request.UserHostAddress;
    }

    if (input != null)
    {
        return string.Format("Your IP address is {0}.", visitorsIpAddr);
    }
    return visitorsIpAddr;
}

Above code gives me actual address on computers without proxy, But those who have proxy setting it gives me the IP address of the proxy server.

Any idea?

Upvotes: 1

Views: 2431

Answers (1)

Bhushan Firake
Bhushan Firake

Reputation: 9448

StackExchange DataExplorer App also determines the IP address of the user behind proxy using following function. You can check it out.

        /// <summary>
        /// When a client IP can't be determined
        /// </summary>
        public const string UnknownIP = "0.0.0.0"; 

        private static readonly Regex _ipAddress = new Regex(@"\b([0-9]{1,3}\.){3}[0-9]{1,3}$",
                                                         RegexOptions.Compiled | RegexOptions.ExplicitCapture);

       /// <summary>
       /// returns true if this is a private network IP
       /// http://en.wikipedia.org/wiki/Private_network
       /// </summary>
         private static bool IsPrivateIP(string s)
         {
            return (s.StartsWith("192.168.") || s.StartsWith("10.") || s.StartsWith("127.0.0."));
         }
        public static string GetRemoteIP(NameValueCollection ServerVariables)
        {
            string ip = ServerVariables["REMOTE_ADDR"]; // could be a proxy -- beware
            string ipForwarded = ServerVariables["HTTP_X_FORWARDED_FOR"];

            // check if we were forwarded from a proxy
            if (ipForwarded.HasValue())
            {
                ipForwarded = _ipAddress.Match(ipForwarded).Value;
                if (ipForwarded.HasValue() && !IsPrivateIP(ipForwarded))
                    ip = ipForwarded;
            }

            return ip.HasValue() ? ip : UnknownIP;
        }

Here HasValue() is an extension defined in another class as below:

public static class Extensions
{
    public static bool HasValue(this string s)
    {
        return !string.IsNullOrEmpty(s);
    }
}

Upvotes: 3

Related Questions