Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function range2cidr($ip_start, $ip_end) {
- static $cidr2hosts;
- if(empty($cidr2hosts)){
- $cidr2hosts = array(
- 32 => 1,
- 31 => 2,
- 30 => 4,
- 29 => 8,
- 28 => 16,
- 27 => 32,
- 26 => 64,
- 25 => 128,
- 24 => 256,
- 23 => 512,
- 22 => 1024,
- 21 => 2048,
- 20 => 4096,
- 19 => 8192,
- 18 => 16384,
- 17 => 32768,
- 16 => 65536,
- 15 => 131072,
- 14 => 262144,
- 13 => 524288,
- 12 => 1048576,
- 11 => 2097152,
- 10 => 4194304,
- 9 => 8388608,
- 8 => 16777216,
- 7 => 33554432,
- 6 => 67108864,
- 5 => 134217728,
- 4 => 268435456,
- 3 => 536870912,
- 2 => 1073741824,
- 1 => 2147483648,
- 0 => 4294967296
- );
- }
- $arr_start = explode(".", $ip_start);
- $arr_end = explode(".", $ip_end);
- $bin_start = "";
- $bin_end = "";
- foreach($arr_start as $a){
- $bin_start.= str_pad(decbin($a), 8, "0", STR_PAD_LEFT);
- }
- foreach($arr_end as $a){
- $bin_end.= str_pad(decbin($a), 8, "0", STR_PAD_LEFT);
- }
- $cidr = 0;
- for($x=0;$x<strlen($bin_start);$x++){
- if($bin_start[$x] == $bin_end[$x]){
- $cidr++;
- } else {
- break;
- }
- }
- $host_count = ~(ip2long($ip_start) ^ ip2long($ip_end)) * -1;
- $cidrs = array();
- if($cidr2hosts[$cidr] != $host_count){
- // we have a non-cidr range, break it up and find them all
- $ranges = array();
- $new_end = long2ip(ip2long($ip_end) - ($cidr2hosts[$cidr] - $host_count));
- $ranges[] = array($ip_start, $new_end);
- $new_start = long2ip(ip2long($new_end) + 1);
- $ranges[] = array($new_start, $ip_end);
- foreach($ranges as $range){
- $cidrs = array_merge($cidrs, call_user_func_array("range2cidr", $range));
- }
- } else {
- $cidrs = array("$ip_start/$cidr");
- }
- return $cidrs;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement