Skip to content

Instantly share code, notes, and snippets.

@thsutton
Created March 17, 2011 04:23
Show Gist options
  • Save thsutton/873831 to your computer and use it in GitHub Desktop.
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.
<?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