Getting list IPs from CIDR notation in PHP

前端 未结 13 1339
慢半拍i
慢半拍i 2020-12-08 05:38

Is there a way (or function/class) to get the list of IP addresses from a CIDR notation?

For example, I have 73.35.143.32/27 CIDR and want to get the list of all IP\

13条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 06:02

    I had some problems with the previous versions, various PHP errors like undefined offset etc.

    I found what I think is a better way to do it without the errors as detailed below.

    This takes IPV4 CIDR notation IP addresses and can be used to get the start/end IP addresses of the CIDR range or count the total number of IP addresses in a database of IP addresses.

        $count = 0;
        $result = $sia_db_con->query("SELECT `ip_address` FROM `ip4` WHERE `ip_ban_active`='True' ORDER BY ip4.added ASC");
    while ($row = $result->fetch_array()) {
        $pos = strpos($row[0], "/");
        $ip_arr = [0 => substr($row[0], 0, $pos), 1 => substr($row[0], $pos+1)];
        $start = cidr2ip($ip_arr)[0];
        $end = cidr2ip($ip_arr)[1];
        $count = $count + (ip2long($end) - ip2long($start)) + 1;
    }
        unset($result, $row, $pos, $ip_arr, $start, $end, $range);
    
    function cidr2ip($cidr) {
        $start = ip2long($cidr[0]);
        $nm = $cidr[1];
        $num = pow(2, 32 - $nm);
        $end = $start + $num - 1;
        $range = [0 => $cidr[0], 1 => long2ip($end)];
        unset($start, $nm, $num, $end);
        return $range;
    }
    

    The secret here is the way in which I create the $ip_arr variable. Rather than using PHP explode, I set the array dimensions manually for each IP address. This is of course a database version of the code and cycles through all IP addresses in the database which meet the search criteria.

提交回复
热议问题