LocustHorde
LocustHorde

Reputation: 6399

How to pass HTTP_X_FORWARDED_FOR to aspx pages from IIS

I have my site running on Amazon ELB. I need to capture client's IP address for something we do on the site - it's not ideal, but we definitely need the IP for now.

This used to work great on a dedicated server. But since moving to ELB, I only get ELB's internal ip address as client's ip address when I use Request.UserHostAddress

Going from some blogs I added X-Forwarded-For and even though my IIS logs have right client IP, that IP is not passed to the actual web pages..

Infact, there is no such field in the header.. or anything close to that in the header.

Inspecting the Request.Headers.ToString() gives me my session cookies, other cookies, client browser (correctly) and other such things but there is nothing about any IP. In fact, I cannot even see the elb's static ip.

Request.Headers["HTTP_X_FORWARDED_FOR"] is always null, understandably.

How do I get the real client IP from C#, please?

Upvotes: 0

Views: 5975

Answers (2)

Scott Munro
Scott Munro

Reputation: 13576

In my testing, the client IP address was populated by the Elastic Load Balancer in both of the following cases.

Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

Request.Headers["X-Forwarded-For"];

Note that the format of these variables is not necessarily just the client IP address. If the request is forwarded multiple times then the server IP addresses will be appended with a comma and a space as separator.

See Amazon's Elastic Load Balancing Developer Guide for further details (search for X-Forwarded-For).

Upvotes: 1

iamserious
iamserious

Reputation: 5475

I did something similar a few days ago!

I had to use Request.ServerVariables and look for REMOTE_ADDR to find the client IP.

Something like this:

if (Request.ServerVariables["REMOTE_ADDR"] != null)
{
    string userIP = Request.ServerVariables["REMOTE_ADDR"]; 
}

That worked for me..

Upvotes: 1

Related Questions