使用PHP将大型CIDR块拆分为更小的块

时间:2013-09-19 21:04:49

标签: php cidr

我试过搜索论坛,却无法在任何地方找到它。发现了一些会使CIDR Block完全分开的东西,但我需要单独使用2个功能。

第一个函数将采用比/ 24更大的CIDR块并将其分成/ 24个块。

我实际上已经完成的第二个功能,然后将每个/ 24分成256个IP地址。答案可以在这里找到。 Exploding given IP range with the PHP

所以我试图想出如何创建一个传递一个/ 23或更大的CIDR块的函数并将其分解为/ 24s

例:
输入:BreakTo24(10.0.0.0/22)

输出:
10.0.0.0/24
10.0.1.0/24
10.0.2.0/24
10.0.3.0/24

编辑:我意识到我没有发布我的代码尝试,这可能使得这更难以帮助。这是代码:

function BreakTo24($CIDR){
    $CIDR = explode ("/", $CIDR);
    //Math to determine if the second part of the array contains more than one /24, and if so how many.

1 个答案:

答案 0 :(得分:2)

我(通过IRC提供了一些帮助)发现我无效地执行此操作并需要使用ip2long函数。

我对此进行了测试,并执行了我想要的操作。这是我完成的代码,希望有人会发现它很有用。

// Function to take greater than a /24 CIDR block and make it into a /24
Function BreakTo24($CIDR)
{
    $CIDR = explode("/", $CIDR); // this breaks the CIDR block into octlets and /notation
    $octet = ip2long($CIDR[0]); //turn the first 3 octets into a long for calculating later
    $NumberOf24s = pow(2,(24-$CIDR[1]))-1; //calculate the number of /24s in the CIDR block
    $OutputArray = array();
    for ($i=-256; $i<256 * $NumberOf24s; $OutputArray[] = (long2ip($octet + ($i += 256)))); //fancy math to output each /24
    return $OutputArray; //returns an array of ranges

}