George Kosmidis

Microsoft MVP | Speaks of Azure & .NET | Founder of Munich .NET
Building tomorrow @
slalom
slalom

C#: Getting a user IP behind a proxy (HTTP_X_FORWARDED_FOR)

by George Kosmidis / Published 10 years ago, modified 3 years ago

Did you know that HTTP_X_FORWARDED_FOR can return multiple IPs? According to http://en.wikipedia.org/wiki/X-Forwarded-For the format is:

X-Forwarded-For: client, proxy1, proxy2

So you just need:


public static string GetUserIP()
{
    var ip = String.IsNullOrWhiteSpace( HttpContent.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ) 
	     ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
	     : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

    if (ip.Contains(",")) {
		ip = ip.Split(',').First().Trim();
	}
    return ip;
}

Simple as that!

This page is open source. Noticed a typo? Or something unclear?
Edit Page Create Issue Discuss
Microsoft MVP - George Kosmidis

My next events!

Online
Online event
Azure Architecture Icons - SVGs, PNGs and draw.io libraries