I\'m looking for quick/simple method for matching a given IP4 dotted quad IP to a CIDR notation mask.
I have a bunch of IPs I need to see if they match a range of IP
I want to have you look at my few lines. The examples that people suggested before me don't seem to work. One reason being, as far as I understand it, is that CIDR mask bits are binary numbers, so the bit shift must be done on a binary number. I have tried converting the long IP's into binaries, but ran into a max binary number limit. OK, here my few lines ... I await your comments.
function cidr_match($ipStr, $cidrStr) {
$ipStr = explode('.', $ipStr);
foreach ($ipStr as $key => $val) {
$ipStr[$key] = str_pad(decbin($val), 8, '0', STR_PAD_LEFT);
}
$ip = '';
foreach ($ipStr as $binval) {
$ip = $ip . $binval;
}
$cidrArr = explode('/',$cidrStr);
$maskIP = explode('.', $cidrArr[0]);
foreach ($maskIP as $key => $val) {
$maskIP[$key] = str_pad(decbin($val), 8, '0', STR_PAD_LEFT);
}
$maskIP = '';
foreach ($ipStr as $binval) {
$maskIP = $maskIP . $binval;
}
$maskBits = 32 - $cidrArr[1];
return (($ip>>$maskBits) == ($maskIP>>$maskBits));
}