Created
March 17, 2011 04:23
-
-
Save thsutton/873831 to your computer and use it in GitHub Desktop.
Function to check membership of an IPv4 address in an IPv4 CIDR block.
This file contains 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
<?php | |
/** | |
* Check whether a IPv4 CIDR notation block contains an IP address. | |
* | |
* @param $cidr string | |
* An IPv4 CIDR block like "192.168.56.0/24". | |
* @param $ip string | |
* An IPv4 address like "192.168.56.101". | |
* @return bool | |
* TRUE iff $ip is within the $cidr block. | |
*/ | |
function ip_in_block($cidr, $ip) { | |
list($addr, $length) = explode('/', $cidr, 2); | |
$length = $length * 1; | |
$zeros = 32 - $length; | |
$mask = (0xFFFFFFFF >> $zeros) << $zeros; | |
$addr = ip2long($addr); | |
$ip = ip2long($ip); | |
return ($addr & $mask) == ($ip & $mask); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment