One of my non-programmer-but-in-IT friends came to me last week, asking help to chunk a range of IPv4 addresses into N small chunks. And, here's the PHP code I came up with within 10 mins.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Copyright (C) 2016 Prabhas Gupte | |
* | |
* This is free script: you can redistribute it and/or modify | |
* it under the terms of the GNU General Public License as published by | |
* the Free Software Foundation, either version 3 of the License, or | |
* (at your option) any later version. | |
* | |
* This script is distributed in the hope that it will be useful, | |
* but WITHOUT ANY WARRANTY; without even the implied warranty of | |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
* GNU General Public License for more details. | |
* | |
* You should also see <http://www.gnu.org/licenses/gpl.txt> | |
*/ | |
function chunkIPRange($ipRange, $numberOfChunks = 2) { | |
list($startIP, $endIP) = explode('-', $ipRange); | |
$startIPNumeric = ip2long($startIP); | |
$endIPNumeric = ip2long($endIP); | |
$expandedRange = range($startIPNumeric, $endIPNumeric); | |
$size = count($expandedRange); | |
$chunkSize = floor($size / $numberOfChunks) + ($size % $numberOfChunks); | |
$rangeChunks = array_chunk($expandedRange, $chunkSize); | |
$chunkNumber = 0; | |
$chunks = array(); | |
foreach ($rangeChunks as &$chunk) { | |
$chunkStart = array_shift($chunk); | |
$chunkEnd = array_pop($chunk); | |
$chunkStart = long2ip($chunkStart); | |
$chunkEnd = long2ip($chunkEnd); | |
$chunks[$chunkNumber] = (($chunkStart !== $chunkEnd) && ($chunkEnd !== '0.0.0.0')) ? "$chunkStart-$chunkEnd" : "$chunkStart"; | |
$chunkNumber++; | |
} | |
unset($rangeChunks); | |
return $chunks; | |
} // chunkIPRange | |
print_r(chunkIPRange('10.10.10.1-10.10.20.10', 3)); | |
print_r(chunkIPRange('172.16.0.1-172.16.1.10')); | |
?> |
Once you have this number, call array_chunk() to create chunks. Finally, iterate over them, get start and end IP of each of them (which are still long numbers), convert them back to IPv4 address using long2ip() and create the range string for them.
Do you find it useful? Copy it! Have any suggestion, let me know in the comment!!