Advertisement
Guest User

IP Range 2 CIDR

a guest
May 11th, 2010
2,846
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.20 KB | None | 0 0
  1. function range2cidr($ip_start, $ip_end) {
  2.  
  3.     static $cidr2hosts;
  4.  
  5.     if(empty($cidr2hosts)){
  6.  
  7.         $cidr2hosts = array(
  8.             32 => 1,
  9.             31 => 2,
  10.             30 => 4,
  11.             29 => 8,
  12.             28 => 16,
  13.             27 => 32,
  14.             26 => 64,
  15.             25 => 128,
  16.             24 => 256,
  17.             23 => 512,
  18.             22 => 1024,
  19.             21 => 2048,
  20.             20 => 4096,
  21.             19 => 8192,
  22.             18 => 16384,
  23.             17 => 32768,
  24.             16 => 65536,
  25.             15 => 131072,
  26.             14 => 262144,
  27.             13 => 524288,
  28.             12 => 1048576,
  29.             11 => 2097152,
  30.             10 => 4194304,
  31.             9  => 8388608,
  32.             8  => 16777216,
  33.             7  => 33554432,
  34.             6  => 67108864,
  35.             5  => 134217728,
  36.             4  => 268435456,
  37.             3  => 536870912,
  38.             2  => 1073741824,
  39.             1  => 2147483648,
  40.             0  => 4294967296
  41.         );
  42.     }
  43.  
  44.     $arr_start = explode(".", $ip_start);
  45.     $arr_end = explode(".", $ip_end);
  46.  
  47.     $bin_start = "";
  48.     $bin_end = "";
  49.  
  50.     foreach($arr_start as $a){
  51.  
  52.         $bin_start.= str_pad(decbin($a), 8, "0", STR_PAD_LEFT);
  53.     }
  54.  
  55.     foreach($arr_end as $a){
  56.         $bin_end.= str_pad(decbin($a), 8, "0", STR_PAD_LEFT);
  57.     }
  58.  
  59.     $cidr = 0;
  60.     for($x=0;$x<strlen($bin_start);$x++){
  61.         if($bin_start[$x] == $bin_end[$x]){
  62.             $cidr++;
  63.         } else {
  64.             break;
  65.         }
  66.     }
  67.  
  68.     $host_count = ~(ip2long($ip_start) ^ ip2long($ip_end)) * -1;
  69.  
  70.     $cidrs = array();
  71.  
  72.     if($cidr2hosts[$cidr] != $host_count){
  73.  
  74.         // we have a non-cidr range, break it up and find them all
  75.  
  76.         $ranges = array();
  77.  
  78.         $new_end = long2ip(ip2long($ip_end) - ($cidr2hosts[$cidr] - $host_count));
  79.  
  80.         $ranges[] = array($ip_start, $new_end);
  81.  
  82.         $new_start = long2ip(ip2long($new_end) + 1);
  83.         $ranges[] = array($new_start, $ip_end);
  84.  
  85.         foreach($ranges as $range){
  86.             $cidrs = array_merge($cidrs, call_user_func_array("range2cidr", $range));
  87.         }
  88.  
  89.     } else {
  90.  
  91.         $cidrs = array("$ip_start/$cidr");
  92.  
  93.     }
  94.  
  95.     return $cidrs;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement