如何组合数组中的IP并获取范围?

时间:2016-12-05 13:26:14

标签: php arrays ip range subnet

例如,我有一个包含此ips的数组:

$array_ips = array();
$array_ips[] = "32.16.8.133"; 
$array_ips[] = "32.16.4.247";
$array_ips[] = "32.16.8.184";
$array_ips[] = "32.16.8.127";
$array_ips[] = "32.16.8.134";
$array_ips[] = "32.16.2.154";
$array_ips[] = "32.16.2.153";
$array_ips[] = "32.16.2.150";
sort($array_ips);

我需要的是IP-Ranges。 对于示例,我需要使用:

返回一个数组
32.16.2.150/29
32.16.4.247/32
32.16.8.127/29

但我现在不知道该怎么做。

我尝试了这样的事情:

$start = ip2long("32.16.2.150");
$end = ip2long("32.16.2.154");
$range = range($start, $end);
$count_ips = count(array_map('long2ip', $range));
echo $count_ips;
if($count_ips <= 1){
    echo '/32';
} else if($count_ips <= 2){
    echo '/30';
} else if($count_ips <= 6){
    echo '/29';
} else if($count_ips <= 14){
    echo '/28';
} else if($count_ips <= 30){
    echo '/37';
} else if($count_ips <= 62){
    echo '/26';
} else if($count_ips <= 126){
    echo '/25';
} else if($count_ips <= 254){
    echo '/24';
}

0 个答案:

没有答案