Match IP-Mask

This functions takes an IP-mask and an IP and returns true if the IP matches the given mask. A mask can be of the form 192.168.0.0/16 or 192.168.0.0/255.255.0.0 or even with long numbers.

ipmatch.inc.php
function ipmatch($mask, $ip) {
    list($mip, $mmask) = explode('/', $mask, 2);
    if (strpos($ip, '.') !== false) $ip = ip2long($ip);
    $ip = decbin($ip);
    if (strpos($mip, '.') !== false) $mip = ip2long($mip);
    $mip = decbin($mip);
    if (strpos($mmask, '.') !== false) $mmask = decbin(ip2long($mmask));  // convert subnet to mask
        elseif ($mmask <= 32) $mmask = str_repeat('1', $mmask) . str_repeat('0', (32-$mmask));  // convert numeric mask to binary number
        else $mmask = decbin($mmask);
    // PHP doesn't like this large numbers, so had to convert to binary (0/1-string)
    $matches = true;
    for ($i=0;$i<32;$i++) {
        if ($mmask{$i} == '1' && ($ip{$i} != $mip{$i})) {
            $matches = false;
            break;
        }
    }
    return $matches;
}

 
snippets/php/match-ip.txt · Last modified: 2010-01-15 14:41.14 by mbirth
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki Contents powered by Club-Mate Contents powered by BassDrive.com Labelled with ICRA