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?