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,, 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 = "";
	return ip;

Leave a Reply

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