Matching an IP to a CIDR mask in PHP 5?

前端 未结 13 1085
无人共我
无人共我 2020-11-28 04:04

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

相关标签:
13条回答
  • 2020-11-28 04:46

    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:

    0 讨论(0)
提交回复
热议问题