Getting list IPs from CIDR notation in PHP

前端 未结 13 1338
慢半拍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:06

    Extension to @jonavon 's answer. If you need flat list of IPs. You can convert his function like below.

    function cidrToRange($value) {
        $range = array();
        $split = explode('/', $value);
        if (!empty($split[0]) && is_scalar($split[1]) && filter_var($split[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            $rangeStart = ip2long($split[0]) & ((-1 << (32 - (int)$split[1])));
            $rangeEnd = ip2long($split[0]) + pow(2, (32 - (int)$split[1])) - 1;
    
            for ($i = $rangeStart; $i <= $rangeEnd; $i++) {
                $range[] = long2ip($i);
            }
            return $range;
        } else {
            return $value;
        }
    }
    

提交回复
热议问题