George Kosmidis

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

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

by George Kosmidis / Published 11 years and 2 months ago, modified 4 years ago

Did you know that HTTP_X_FORWARDED_FOR can return multiple IPs? According to 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
Azure Architecture Icons - SVGs, PNGs and libraries