Check whether or not a CIDR subnet contains an IP address

If only using IPv4:

  • use ip2long() to convert the IPs and the subnet range into long integers
  • convert the /xx into a subnet mask
  • do a bitwise ‘and’ (i.e. ip & mask)’ and check that that ‘result = subnet’

something like this should work:

function cidr_match($ip, $range)
{
    list ($subnet, $bits) = explode("https://stackoverflow.com/", $range);
    if ($bits === null) {
        $bits = 32;
    }
    $ip = ip2long($ip);
    $subnet = ip2long($subnet);
    $mask = -1 << (32 - $bits);
    $subnet &= $mask; # nb: in case the supplied subnet wasn't correctly aligned
    return ($ip & $mask) == $subnet;
}

Leave a Comment