06 July 2011

PHP function to determine if IP address is private

If you parse an IP address to this function, it will return whether or not the ip address is private (RFC1918). Not sure if there is a better way of achieving this?

$private = DetermineLocal('192.168.1.1');
if ($private) {echo 'This IP address is a private IP address';} else
echo 'This IP address is not private';

function DetermineLocal($ip) {
$private_ip = array("/^0\./", "/^127\.0\.0\.1/", "/^192\.168\..*/",
"/^172\.((1[6-9])|(2[0-9])|(3[0-1]))\..*/", "/^10\..*/", "/^224\..*/",
"/^240\..*/");
while (list ($key, $val) = each ($private_ip)) {
if (preg_match($val, $ip))
{
return true;
}
}
}
?>

No comments:

Post a Comment