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 recently needed to match an IP address to a CIDR mask and came across this article. Below is a slightly different approach based on the ideas above and includes a check on the CIDR input. The function returns false if an incorrect CIDR format is submitted.
I posted this solution for anyone who needs a turn-key function that has been tested.
/**
* Validates subnet specified by CIDR notation.of the form IP address followed by
* a '/' character and a decimal number specifying the length, in bits, of the subnet
* mask or routing prefix (number from 0 to 32).
*
* @param $ip - IP address to check
* @param $cidr - IP address range in CIDR notation for check
* @return bool - true match found otherwise false
*/
function cidr_match($ip, $cidr) {
$outcome = false;
$pattern = '/^(([01]?\d?\d|2[0-4]\d|25[0-5])\.){3}([01]?\d?\d|2[0-4]\d|25[0-5])\/(\d{1}|[0-2]{1}\d{1}|3[0-2])$/';
if (preg_match($pattern, $cidr)){
list($subnet, $mask) = explode('/', $cidr);
if (ip2long($ip) >> (32 - $mask) == ip2long($subnet) >> (32 - $mask)) {
$outcome = true;
}
}
return $outcome;
}
Test data is shown in the image below: