Due to a web server’s proxy or the server is clustered (particularly with “cloud” based hosting), the server variable WordPress uses does not reflect the IP address of the posting user. Instead the IP address is the internal private LAN address of the web server’s network. This causes problems when trying to blacklist spammers or use a plugin like Akismet.
To workaround this IP address issue, you will need to modify the $_SERVER["REMOTE_ADDR"] variable by editing the “wp-config.php” in your WordPress root directory:
- Download and backup your wp-config.php configuration file.
- Open your WordPress configuration file and add the following code after the named constant definitions:
/* By Grant Burton @ BURTONTECH.COM (11-30-2008): IP-Proxy-Cluster Fix */
function checkIP($ip) {
if (!empty($ip) && ip2long($ip)!=-1 && ip2long($ip)!=false) {
$private_ips = array (
array('0.0.0.0','2.255.255.255'),
array('10.0.0.0','10.255.255.255'),
array('127.0.0.0','127.255.255.255'),
array('169.254.0.0','169.254.255.255'),
array('172.16.0.0','172.31.255.255'),
array('192.0.2.0','192.0.2.255'),
array('192.168.0.0','192.168.255.255'),
array('255.255.255.0','255.255.255.255')
);
foreach ($private_ips as $r) {
$min = ip2long($r[0]);
$max = ip2long($r[1]);
if ((ip2long($ip) >= $min) && (ip2long($ip) <= $max)) return false;
}
return true;
} else {
return false;
}
}
function determineIP() {
if (checkIP($_SERVER["HTTP_CLIENT_IP"])) {
return $_SERVER["HTTP_CLIENT_IP"];
}
foreach (explode(",",$_SERVER["HTTP_X_FORWARDED_FOR"]) as $ip) {
if (checkIP(trim($ip))) {
return $ip;
}
}
if (checkIP($_SERVER["HTTP_X_FORWARDED"])) {
return $_SERVER["HTTP_X_FORWARDED"];
} elseif (checkIP($_SERVER["HTTP_X_CLUSTER_CLIENT_IP"])) {
return $_SERVER["HTTP_X_CLUSTER_CLIENT_IP"];
} elseif (checkIP($_SERVER["HTTP_FORWARDED_FOR"])) {
return $_SERVER["HTTP_FORWARDED_FOR"];
} elseif (checkIP($_SERVER["HTTP_FORWARDED"])) {
return $_SERVER["HTTP_FORWARDED"];
} else {
return $_SERVER["REMOTE_ADDR"];
}
}
//Override server variable for WordPress comments
$_SERVER["REMOTE_ADDR"] = determineIP();
Caution should be used since many of these variables can be spoofed by a client, so don’t use them for authentication or access control. The functions could be easily adapted for other web applications though.
Tags: 172.16.10.1, akismet, comment, HTTP_CLIENT_IP, HTTP_FORWARDED, HTTP_X_CLUSTER_CLIENT_IP, HTTP_X_FORWARDED, HTTP_X_FORWARDED_FOR, incorrect ip, ip address, PHP, private ip, REMOTE_ADDR, Spam, Wordpress, wp-config.php
[...] Grant Burton has a better mechanism for detecting visitor’s real IP address. He is checking for local network IP address (for example -192.168.x.x) first and based on that he is deciding which one to take. You may not like storing the 192.168.x.x etc., as it will be useless. [...]