Advertisement
hexasoft

Converting IP address ranges into CIDR format

May 16th, 2018
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.72 KB | None | 0 0
  1. /****************************************************************************************************************/
  2. /* Description: This snippet is provide simple way to help user Converting IP address ranges into CIDR format   */
  3. /*              suggestions for different city locations across the country.                                    */
  4. /*              There are 1 steps in this snippet. For information, please visit IP2Location tutorial page at:  */
  5. /*https://www.ip2location.com/tutorials/how-to-convert-ip-address-range-into-cidr                               */         
  6. /****************************************************************************************************************/
  7.  
  8. <?php
  9.     function iprange2cidr($ipStart, $ipEnd){
  10.         if (is_string($ipStart) || is_string($ipEnd)){
  11.             $start = ip2long($ipStart);
  12.             $end = ip2long($ipEnd);
  13.         }
  14.         else{
  15.             $start = $ipStart;
  16.             $end = $ipEnd;
  17.         }
  18.  
  19.         $result = array();
  20.  
  21.         while($end >= $start){
  22.             $maxSize = 32;
  23.             while ($maxSize > 0){
  24.                 $mask = hexdec(iMask($maxSize - 1));
  25.                 $maskBase = $start & $mask;
  26.                 if($maskBase != $start) break;
  27.                 $maxSize--;
  28.             }
  29.             $x = log($end - $start + 1)/log(2);
  30.             $maxDiff = floor(32 - floor($x));
  31.  
  32.             if($maxSize < $maxDiff){
  33.                 $maxSize = $maxDiff;
  34.             }
  35.  
  36.             $ip = long2ip($start);
  37.             array_push($result, "$ip/$maxSize");
  38.             $start += pow(2, (32-$maxSize));
  39.         }
  40.         return $result;
  41.     }
  42.  
  43.     function iMask($s){
  44.         return base_convert((pow(2, 32) - pow(2, (32-$s))), 10, 16);
  45.     }
  46.  
  47. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement