Reputation: 5
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?
Upvotes: 0
Views: 532
Reputation: 780909
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);
}
Upvotes: 0