puffpio [dot] com

puffpio [dot] com

David Pio  //  software developer, technology geek, gadget whore, motorsports junkie, video game nerd, partner engineer at Facebook

Mar 12 / 12:22pm

Load Balancing and x-forwarded-for

This is a pretty common mistake to make:
If your ASP.net site requires you to capture the IP address of the user hitting the site, you use Request.UserHostAddress

If you are behind a load balancer or some other proxy, that address actually changes to take the address of the load balancer/proxy :sadpanda:
Now a good load balancer will append an HTTP header "x-forward-for" which contains the original IP address.

So what's a guy like me to do?  Anywhere I used

Request.UserHostAddress
, change it to be
Request.Headers["x-forwarded-for"] ?? Request.UserHostAddress
. There all better. It will fall back to UserHostAddress if x-forwarded-for is not in the collection of HTTP headers, and looking up the header is not case sensitive so we are OK there.

 

Filed under  //  asp.net   ip address   load balancer   x-forwarded-for