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) ) == 
ip2long($subnet))
    { 
        return true;
    }

    return false;
}

Example results

cidr_match("1.2.3.4", "0.0.0.0/0"): true
cidr_match("127.0.0.1", "127.0.0.1/32"): true
cidr_match("127.0.0.1", "127.0.0.2/32"): false

Sources:

http://www.php.net/manual/en/function.ip2long.php#82397

http://stackoverflow.com/questions/594112/matching-an-ip-to-a-cidr-mask-in-php5

Leave a Reply

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