George Kosmidis

Microsoft MVP | Cloud Solutions Architect | .NET Software Engineer | Organizer of Munich .NET Meetup | Speaker

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

by George Kosmidis / Published 9 years and 5 months ago, modified 2 years and 4 months 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

My next events!

Online event
Online event
Mindspace Salvatorplatz (Salvatorplatz 3, München, BY, Germany 80333)