How to check if an ip address matches a CIDR

When working in the area of application security, you may come across situations where you need to make sure that only certain servers are allowed to access your web service. Usually checking the ip address is a decent way of making such guarantees.

You can use a function as follows:

function cidr_match($ip, $cidr)
    list($subnet, $mask) = explode('/', $cidr);

    if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1) ) == 
        return true;

    return false;

Example results

cidr_match("", ""): true
cidr_match("", ""): true
cidr_match("", ""): false


Leave a Reply

Your email address will not be published. Required fields are marked *