Gotcha: HTTP_X_FORWARDED_FOR returns multiple IP addresses

I hit a small gotcha this evening. A visitor to Developer Fusion reported that they couldn't gain access to the site at all, because our IP address detection logic was failing. We were checking the "HTTP_X_FORWARDED_FOR" header for an IP address, before falling back to REMOTE_ADDR, turning the IP into a long integer, and doing an IP-to-country lookup in our database. Which seemed safe enough!

As it turns out, HTTP_X_FORWARDED_FOR can sometimes have a comma delimited list of IP addresses - so what we actually needed to be doing was take the last IP address in that list, before doing our conversion to an integer.

Thanks go out to Francois Botha, one of our visitors, for helping me track down this issue!

Published 19 June 2007 10:00 PM by James Crowley
Filed under:

Comments

# Kim said on 23 June, 2007 08:10 PM

Thank you James for solving this problem. We will update the source codes in IP2Location.

# Boris Yeltsin's Zombie said on 26 June, 2007 06:36 AM

Damn. I've written apps using this property and never knew it could send more than one IP. Thanks for the heads-up :)

# jspurlin said on 11 July, 2007 09:39 AM

In which order is the comma delimited list returned?. For example, if I am trying to get "the" original ip, is it first in the list (always)?

# neokio said on 03 September, 2007 06:47 AM

i ran into this about a year ago, and wrote this snippet as a workaround. Only tested it with a few proxies (Google translate, etc.), so no guarantees...

if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))

$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];

else

$ip = $_SERVER['REMOTE_ADDR'];

//  When viewed through an anonymous proxy, the address string

// contans multiple ip#s separated hy commas. This fixes that.

$ip_array = explode(",", $ip);

$ip = $ip_array[0];

# Viral said on 01 May, 2008 07:44 AM

:neokio

instead of using first member from $_SERVER['HTTP_X_FORWARDED_FOR'] retuning comma delimited value.

shouldn't we be using the last member of the array ?

something like,

$ip = $ip_array[ count($ip_array) - 1 ];

???

# Scotty said on 10 June, 2008 09:01 AM

Thanks Viral and Neokio. The added line from Viral looks good and works for me. I was looking for a function like explode... so this is perfect.

Leave a Comment

(required) 
(required) 
(optional)
(required)