首页 > 解决方案 > PHP ip 计算 -> 来自 ipaddress 的段数组

问题描述

我有一个关于 ip 段的请求。

示例:我有一个 ip 段:10.10.10.0/8

我想在上述范围内获得 /24 的数组(使用 cidr 输入 ip 段)我尝试使用如下内容:

    $c_segment = explode("/", $segment);
    $c_mask = ipv4::CIDRtoMask($c_segment[1]);

    $input = new stdClass();
    $input->ip = $c_segment[0];
    $input->netmask = $c_mask;
    $input->ip_int = ip2long($input->ip);
    $input->netmask_int = ip2long($input->netmask);
    // Network is a logical AND between the address and netmask
    $input->network_int = $input->ip_int & $input->netmask_int;
    $input->network = long2ip($input->network_int);
    // Broadcast is a logical OR between the address and the NOT netmask
    $input->broadcast_int = $input->ip_int | (~ $input->netmask_int);
    $input->broadcast = long2ip($input->broadcast_int);

    $ranges = ipv4::rangeToCIDRList($input->ip,$input->broadcast);
    natsort($ranges);

    $start_seg =  ip2long($input->network);
    $end_seg = $ranges[sizeof($ranges)-1];
    $end_seg = explode("/",$end_seg);
    $end_seg = ip2long($end_seg[0]);
    $iterations = round(log($end_seg));

其中 $iterations 应该是 /24 的数量.. 但我不确定这是否是正确的方法(或者上面是否是最好的方法..)

我的最终结果应该可以帮助我打印每页/24 个 IP 地址(带有分页选项。(我知道在上面的示例中这将是大量页面..)

最好的

拉斯

标签: phparraysip

解决方案


我知道github.com/S1lentium/IPTools做到了,所以你可以看看它的实现。


推荐阅读