ip_address
- Versions
- 6 – 7
ip_address()
If Drupal is behind a reverse proxy, we use the X-Forwarded-For header instead of $_SERVER['REMOTE_ADDR'], which would be the IP address of the proxy server, and not the client's.
Return value
IP address of client machine, adjusted for reverse proxy.
Code
includes/bootstrap.inc, line 1190
<?php
function ip_address() {
static $ip_address = NULL;
if (!isset($ip_address)) {
$ip_address = $_SERVER['REMOTE_ADDR'];
if (variable_get('reverse_proxy', 0) && array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
// If an array of known reverse proxy IPs is provided, then trust
// the XFF header if request really comes from one of them.
$reverse_proxy_addresses = variable_get('reverse_proxy_addresses', array());
if (!empty($reverse_proxy_addresses) && in_array($ip_address, $reverse_proxy_addresses, TRUE)) {
// If there are several arguments, we need to check the most
// recently added one, i.e. the last one.
$ip_address = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
}
}
}
return $ip_address;
}
?>Login or register to post comments 
Our proxy redirects - LVS
Our proxy redirects a request to itself on a different port, for load balancing benefits, hence the last added ip is 127.0.0.1
The code below provides a answer to this problem, although you have to be careful when updating your install.
function ip_address() {
static $ip_address = NULL;
if (!isset($ip_address)) {
$ip_address = $_SERVER['REMOTE_ADDR'];
if (variable_get('reverse_proxy', 0) && array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
// If an array of known reverse proxy IPs is provided, then trust
// the XFF header if request really comes from one of them.
$reverse_proxy_addresses = variable_get('reverse_proxy_addresses', array());
if (!empty($reverse_proxy_addresses) && in_array($ip_address, $reverse_proxy_addresses, TRUE)) {
// If there are several arguments, we need to check the most
// recently added one, i.e. the last one.
$ip_list = array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
$ip_address = array_pop($ip_list);
while(in_array($ip_address, $reverse_proxy_addresses)){
$ip_address = trim(array_pop($ip_list));
}
}
}
}
return $ip_address;
}