Skip to content

Instantly share code, notes, and snippets.

@mudge
Last active December 20, 2015 12:29
Show Gist options
  • Save mudge/6131760 to your computer and use it in GitHub Desktop.
Save mudge/6131760 to your computer and use it in GitHub Desktop.
A simple function to determine whether an IP is within a CIDR range or not.
<?php
/* A simple function to determine whether an IP is within a range
* or not.
*
* Examples:
*
* withinCIDR('1.2.3.4', '1.2.3.0/24');
* => 1
*
* withinCIDR('1.2.3.4', '1.2.3.4');
* => 1
*
* withinCIDR('1.2.3.4', '1.2.3.0/32');
* =>
*/
function withinCIDR($ip, $cidr)
{
$within = false;
if (strpos($cidr, '/')) {
list($startIp, $prefix) = explode('/', $cidr);
$count = 1 << (32 - $prefix);
$start = ip2long($startIp);
$end = $start + $count;
$within = ip2long($ip) >= $start && ip2long($ip) < $end;
} else {
$within = $ip == $cidr;
}
return $within;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment