I was reading Paul Gregg’s very clear explanation of “classless” ranges comparison when I realized that his code was not as “bare metal” as could be.So, here is the code I’ve been using in nextBBS.It only accepts ranges in the form “x.x.x.x/b” but it’s short and all I needed, really.
function isSubnet($subnet, $ip) {
// Classless (in more than one way) comparison
$cursubnet = explode('/', $subnet);
$longsubnet = ip2long($cursubnet[0]);
$longip = ip2long($ip);
if(count($cursubnet){
// Compare IP itself
return ($longip==$longsubnet);
}
// IPv4 only!
$subnetmask = 0xffffffff << (32-$cursubnet[1]);
return (($longip & $subnetmask) == ($longsubnet & $subnetmask));
}
Comments powered by Talkyard.