Skip to content

Instantly share code, notes, and snippets.

@pmgupte
Last active October 6, 2016 07:04
Show Gist options
  • Save pmgupte/e84d5cc4daed1c9699ed to your computer and use it in GitHub Desktop.
Save pmgupte/e84d5cc4daed1c9699ed to your computer and use it in GitHub Desktop.
PHP function to chunk the given IP address range into multiple ranges of given size.
<?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'));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment