1

This is very very old discussion issue that asked How to get a user's client IP address in ASP.NET? but I really need to know that client is from private network or not, by below code the IP Address always is 192.168.1.1

public static System.Net.IPEndPoint GetOriginIPEndpoint(this System.Web.HttpContext context)
{  
    string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    string ipEndpoint = null; 
    if (!string.IsNullOrEmpty(ipAddress))
    {
        string[] addresses = ipAddress.Split(',');
        if (addresses.Length != 0)
        {
            ipEndpoint = addresses[0];
        }
    } 
    if (ipEndpoint == null)
        ipEndpoint = context.Request.ServerVariables["REMOTE_ADDR"]; 
    if (string.IsNullOrEmpty(ipEndpoint))
    { 
        return null;
    } 
    return ipEndpoint; 
}

HTTP_X_FORWARDED_FOR is null and REMOTE_ADDR is return router IP and checking local Ip:

public static bool IsLocalAddress(this IPEndPoint endpoint)
{
    if (endpoint == null)
        return false;
    return (endpoint.Address.MapToIPv4().ToString().StartsWith("192.168.") ||
        endpoint.Address.MapToIPv4().ToString().StartsWith("172.16.") ||
        endpoint.Address.MapToIPv4().ToString().StartsWith("10.") ||
        endpoint.Address.MapToIPv4().ToString().StartsWith("127.0.0.1") ||
        endpoint.Address.MapToIPv4().ToString().Equals("0.0.0.1"));
}

and

var address = HttpContext.Current.GetOriginIPEndpoint();
var islocal = address?.IsLocalAddress();//This is always return true

even this below snipped does not help:

string[] variables = new string[]
{
    "HTTP_X_COMING_FROM",
    "HTTP_X_FORWARDED_FOR",
    "HTTP_X_FORWARDED",
    "HTTP_VIA",
    "HTTP_COMING_FROM",
    "HTTP_FORWARDED_FOR",
    "HTTP_FORWARDED",
    "HTTP_FROM",
    "HTTP_PROXY_CONNECTION",
    "HTTP_CLIENT_IP",
    "CLIENT_IP",
    "FORWARDED",
};
foreach (string variable in variables)
{
    string strIPAddress = context.Request.ServerVariables[variable];
    //strIPAddress is always empty
}
string IP = context.Request.Params["HTTP_CLIENT_IP"] ?? context.Request.UserHostAddress;//This is also return 192.168.1.1

is there a solution to get real IP when there is front proxy?

Aria
  • 3,724
  • 1
  • 20
  • 51

1 Answers1

0

You could use an external service like ipify (which you also could host yourself). From its samples:

var httpClient = new HttpClient();
var ip = await httpClient.GetStringAsync("https://api.ipify.org");
Console.WriteLine($"My public IP address is: {ip}");
user7217806
  • 2,014
  • 2
  • 10
  • 12
  • It does not work, because it also always return static IP of network either from private network or through the internet. – Aria Mar 04 '20 at 10:29