duanchifo2866 2018-06-19 19:45 采纳率: 100%
浏览 99
已采纳

PHP如何通过CIDR函数运行IP范围列表?

IP2Location.com has a working PHP function to convert a SINGLE IP range to CIDR format. I want to periodically feed a LIST of IP ranges (an array?) through the function to get a list of CIDR formatted results. I'm not sure how to do that properly with PHP, and perhaps it's the wrong tool? Any guidance appreciated. Here is the function, with sample input/output below:

function iprange2cidr($ipStart, $ipEnd){
    if (is_string($ipStart) || is_string($ipEnd)){
        $start = ip2long($ipStart);
        $end = ip2long($ipEnd);
    }
    else{
        $start = $ipStart;
        $end = $ipEnd;
    }
    $result = array();
    while($end >= $start){
        $maxSize = 32;
        while ($maxSize > 0){
            $mask = hexdec(iMask($maxSize - 1));
            $maskBase = $start & $mask;
            if($maskBase != $start) break;
            $maxSize--;
        }
        $x = log($end - $start + 1)/log(2);
        $maxDiff = floor(32 - floor($x));
        if($maxSize < $maxDiff){
            $maxSize = $maxDiff;
        }
        $ip = long2ip($start);
        array_push($result, "$ip/$maxSize");
        $start += pow(2, (32-$maxSize));
    }
    return $result;
}
function iMask($s){
    return base_convert((pow(2, 32) - pow(2, (32-$s))), 10, 16);
}

Then to test the function, supplying a single range with ipStart of 8.8.8.0 and ipEnd of 8.8.8.16, the CIDR result of the function is an array, echoed using implode:

$ipStart = '8.8.8.0';
$ipEnd = '8.8.8.16';
$ipCidr = iprange2cidr($ipStart, $ipEnd);
echo implode ("<br>", $ipCidr);

The CIDR formatted result is:

8.8.8.0/28
8.8.8.16/32

That works well for a single range. How would you suggest feeding a list of ranges to the ipStart and ipEnd variables, and have the function run through the list, building a final result list?

  • 写回答

1条回答 默认 最新

  • doukanxi4246 2018-06-19 20:25
    关注

    Just loop through the list of ranges, and use array_merge() to append the results to the collection of all results.

    $ranges = [
        ["start" => "8.8.8.0", "end" => "8.8.8.16"],
        ["start" => "192.168.10.5", "end" => "192.168.32.255"],
        ["start" => "10.1.2.32", "end" => "10.1.3.0"]
    ];
    $allCidrs = [];
    foreach ($ranges as $range) {
        $cidr = iprange2cidr($range["start"], $range["end"]);
        $allCidrs = array_merge($allCidrs, $cidr);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题