PHP ip address range check 

Joined:
03/10/2011
Posts:
84

April 05, 2011 11:42:51    Last update: April 05, 2011 11:42:51
Use the ip2long function to check IP address range in PHP. The following code checks to see if an IP address falls in the private network ranges:
#!/usr/bin/php
<?php
function is_private_ip($ip) {
    if (empty($ip) or !ip2long($ip)) {
	return NULL;
    }
 
    $private_ips = array (
	array('10.0.0.0','10.255.255.255'),
	array('172.16.0.0','172.31.255.255'),
	array('192.168.0.0','192.168.255.255')
    );
 
    $ip = ip2long($ip);
    foreach ($private_ips as $ipr) {
	$min = ip2long($ipr[0]);
	$max = ip2long($ipr[1]);
	if (($ip >= $min) && ($ip <= $max)) return true;
    }
 
    return false;
}
 
if ($argc < 2) {
?>
Usage: <?php echo $argv[0]; ?> <ip_adddress>
<?php
} 
else {
    $is_private_ip = is_private_ip($argv[1]);
    if ($is_private_ip) {
	echo "$argv[1] is a private network address\n";
    }
    else if ($is_private_ip === false) {
	echo "$argv[1] is NOT a private network address\n";
    }
    else {
	echo "$argv[1] is NOT a valid IP address\n";
    }
}
?>

Share |
| Comment  | Tags