PHP 想將 CIDR 的 IP 展開,或者要抓 CIDR 最小與最大值的區間,要怎麼做呢?
PHP 將 IPv4 CIDR subnet IP 展開
PHP 將 CIDR IP 展開:
<?php function ip_cidr_list($cidr) { list($ip, $vlsm) = explode('/', $cidr); $start_ip = long2ip((ip2long($ip)) & ((-1 << (32 - (int)$vlsm)))); $ip_count = 1 << (32 - $vlsm); $start = ip2long($start_ip); for ($i = 0; $i < $ip_count; $i++) { $ip = long2ip($start + $i); echo $ip . "\n"; } } print_r(ip_cidr_list('207.64.1.68/28')); // 207.64.1.68, 207.64.1.69, .. 207.64.1.83 print_r(ip_cidr_list('172.224.224.88/29')); // 172.224.224.88,172.224.224.89 .. 172.224.224.95 ?>
PHP 將 CIDR IP 展開取得最小與最大值,抓取範圍區間:
<?php function ip_cidr_range($cidr) { $range = []; $cidr = explode('/', $cidr); $range[0] = long2ip((ip2long($cidr[0])) & ((-1 << (32 - (int)$cidr[1])))); $range[1] = long2ip((ip2long($range[0])) + pow(2, (32 - (int)$cidr[1])) - 1); return $range; } print_r(ip_cidr_range('207.64.1.68/28')); // [207.64.1.64, 207.64.1.79] print_r(ip_cidr_range('172.224.224.88/29')); // [172.224.224.88, 172.224.224.95] ?>