C# getting correct user IP even if HTTP_X_FORWARDED_FOR contains multiple IP Addresses

HTTP_X_FORWARDED_FOR can return multiple IP Addresses, for example 32.122.54.21, 32.122.54.25, 32.122.65.23 following the general format of the field

X-Forwarded-For: client, proxy1, proxy2

Source: Wikipedia / X-Forwarded-For

My approach

public static string GetClientIp()
{
	string ip = string.Empty;

	ip = string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] : System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
	if (ip.Contains(","))
	{
		ip = ip.Split(',').First().Trim();
	}

	if (string.IsNullOrWhiteSpace(ip))
	{
		ip = "0.0.0.0";
	}
	
	return ip;
}
	

Leave a Reply

Your email address will not be published. Required fields are marked *