PHP function isIpInRanges($ip, $ranges)

Function that checks if given IP is within one of given IP ranges.

<?php
/**
 * Checks if given IP is in one of IP ranges
 * @param string|int $ip in format x.x.x.x or unsigned int
 * @param string[] $ranges in format IP/NETMASK
 * @return bool
 */
function isIpInRanges($ip, $ranges)
{
    if (is_numeric($ip))
        $ip_dec = $ip;
    else
        $ip_dec = ip2long($ip);

    foreach ($ranges as $range) {
        if (strpos($range, '/') === false)
            $range .= '/32';

        list($range, $netmask) = explode('/', $range, 2);
        $x = explode('.', $range);
        while (count($x) < 4) $x[] = '0';
        $range = sprintf("%u.%u.%u.%u", $x[0], $x[1], $x[2], $x[3]);
        $range_dec = ip2long($range);

        $wildcard_dec = pow(2, (32 - $netmask)) - 1;
        $netmask_dec = ~$wildcard_dec;

        if (($ip_dec & $netmask_dec) == ($range_dec & $netmask_dec))
            return true;
    }

    return false;
}

// TESTS
var_dump(isIpInRanges('127.0.0.1', [])); // false
var_dump(isIpInRanges('127.0.0.1', ['127.0.0.1'])); // true
var_dump(isIpInRanges('127.0.0.1', ['127.0.0.0/32'])); // false
var_dump(isIpInRanges('127.0.0.1', ['127.0.0.0/24'])); // true
var_dump(isIpInRanges('1.1.1.1', ['1.0.0.0/16', '1.1.0.0/16'])); // true
var_dump(isIpInRanges('192.168.11.11', ['192.168.11/24'])); // true
var_dump(isIpInRanges('192.168.11.11', ['192.168.11/22'])); // true
var_dump(isIpInRanges('192.168.11.11', ['192.168/29'])); // false

var_dump(isIpInRanges(3000000000, ['178.208.94.0'])); // true
var_dump(isIpInRanges(3000000000, ['178/8'])); // true

Leave a Reply

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