Last active
December 20, 2015 12:29
-
-
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.
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
<?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