Getting list IPs from CIDR notation in PHP

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

    Fixed version of Kosmonaft script:

    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));
    
            echo "Number of Hosts:    " . ($bc_long - $nw - 1) . "
    "; echo "Host Range: " . long2ip($nw + 1) . " -> " . long2ip($bc - 1) . "
    ". "
    "; for($zm=1;($nw + $zm)<=($bc_long - 1);$zm++) { echo long2ip($nw + $zm). "
    "; } }

提交回复
热议问题