Matching an IP to a CIDR mask in PHP 5?

前端 未结 13 1125
无人共我
无人共我 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:27

    Perhaps it is useful to someone.

    Convert bit mask into IP mask:

    // convert 12 => 255.240.0.0
    // ip2long('255.255.255.255') == -1
    $ip = long2ip((-1 << (32 - $bit)) & -1);
    

    Convert IP mask into bit mask:

    // convert 255.240.0.0 => 12
    
    // is valid IP
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
        throw new \InvalidArgumentException(sprintf('Invalid IP "%s".', $ip));
    }
    
    // convert decimal to binary
    $mask = '';
    foreach (explode('.', $ip) as $octet) {
        $mask .= str_pad(decbin($octet), 8, '0', STR_PAD_LEFT);
    }
    
    // check mask
    if (strpos('01', $mask) !== false) {
        // valid   11111111111111111111111100000000 -> 255.255.255.0
        // invalid 11111111111111111111111100000001 -> 255.255.255.1
        throw new \InvalidArgumentException(sprintf('IP mask "%s" is not valid.', $ip));
    }
    
    $bit = substr_count($mask, '1'); // bit mask
    

提交回复
热议问题