Matching an IP to a CIDR mask in PHP 5?

前端 未结 13 1096
无人共我
无人共我 2020-11-28 04:04

I\'m looking for quick/simple method for matching a given IP4 dotted quad IP to a CIDR notation mask.

I have a bunch of IPs I need to see if they match a range of IP

13条回答
  •  庸人自扰
    2020-11-28 04:43

    I want to have you look at my few lines. The examples that people suggested before me don't seem to work. One reason being, as far as I understand it, is that CIDR mask bits are binary numbers, so the bit shift must be done on a binary number. I have tried converting the long IP's into binaries, but ran into a max binary number limit. OK, here my few lines ... I await your comments.

    function cidr_match($ipStr, $cidrStr) {
    
    $ipStr = explode('.', $ipStr);
    foreach ($ipStr as $key => $val) {
        $ipStr[$key] = str_pad(decbin($val), 8, '0', STR_PAD_LEFT);
        }
    $ip = '';
    foreach ($ipStr as $binval) {
        $ip = $ip . $binval;
        }
    
    $cidrArr = explode('/',$cidrStr);
    
    $maskIP = explode('.', $cidrArr[0]);
    foreach ($maskIP as $key => $val) {
        $maskIP[$key] = str_pad(decbin($val), 8, '0', STR_PAD_LEFT);
        }
    $maskIP = '';
    foreach ($ipStr as $binval) {
        $maskIP = $maskIP . $binval;
        }
    $maskBits = 32 - $cidrArr[1];
    return (($ip>>$maskBits) == ($maskIP>>$maskBits));  
    }
    

提交回复
热议问题