Getting list IPs from CIDR notation in PHP

前端 未结 13 1361
慢半拍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 05:59

    this returns an array of ips:

    function get_list_ip($ip_addr_cidr){
        $ip_arr = explode("/", $ip_addr_cidr);    
        $bin = "";
    
        for($i=1;$i<=32;$i++) {
            $bin .= $ip_arr[1] >= $i ? '1' : '0';
        }
    
        $ip_arr[1] = bindec($bin);
    
        $ip = ip2long($ip_arr[0]);
        $nm = $ip_arr[1];
        $nw = ($ip & $nm);
        $bc = $nw | ~$nm;
        $bc_long = ip2long(long2ip($bc));
    
        for($zm=1;($nw + $zm)<=($bc_long - 1);$zm++)
        {
            $ret[]=long2ip($nw + $zm);
        }
        return $ret;
    }
    

提交回复
热议问题