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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。