Created
July 10, 2014 19:24
-
-
Save magenx/31522a152bd93650022b to your computer and use it in GitHub Desktop.
CIDR -> IP -> MATCH
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$cidrs = array( | |
'192.168.1.20/27', | |
'192.168.0.10/32' | |
); | |
function cidr_match($ip, $range) | |
{ | |
list ($subnet, $bits) = explode('/', $range); | |
$ip = ip2long($ip); | |
$subnet = ip2long($subnet); | |
$mask = -1 << (32 - $bits); | |
$subnet &= $mask; | |
return ($ip & $mask) == $subnet; | |
} | |
$user_ip = $_SERVER['REMOTE_ADDR']; | |
$validaddr = false; | |
foreach ($cidrs as $addr) | |
if (cidr_match($user_ip, $addr)) { | |
$validaddr = true; | |
break; | |
} | |
if ($validaddr) { | |
echo "CORRECT IP ADDRESS"; | |
} | |
else { | |
echo "INCORRECT IP ADDRESS"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment