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
Perhaps it is useful to someone.
Convert bit mask into IP mask:
// convert 12 => 255.240.0.0
// ip2long('255.255.255.255') == -1
$ip = long2ip((-1 << (32 - $bit)) & -1);
Convert IP mask into bit mask:
// convert 255.240.0.0 => 12
// is valid IP
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
throw new \InvalidArgumentException(sprintf('Invalid IP "%s".', $ip));
}
// convert decimal to binary
$mask = '';
foreach (explode('.', $ip) as $octet) {
$mask .= str_pad(decbin($octet), 8, '0', STR_PAD_LEFT);
}
// check mask
if (strpos('01', $mask) !== false) {
// valid 11111111111111111111111100000000 -> 255.255.255.0
// invalid 11111111111111111111111100000001 -> 255.255.255.1
throw new \InvalidArgumentException(sprintf('IP mask "%s" is not valid.', $ip));
}
$bit = substr_count($mask, '1'); // bit mask