KAYAK2U

April 27, 2011

Optimizin’ IP range to CIDR functions

Looking for helper functions for the latest enhancements to my almost-Alpha version opus led here and here, before I settled on the code here.  It has to do with turning an IP range (123.456.789.0 – 123.456.789.255) into its CIDR equivalent(s) (123.456.789.0/24), a task somewhat more difficult than it might first appear.

The class below, which I've stripped of extraneities (and also of three of its methods) gets right to business in a fast, efficient way without some of the convolutions and conditionals of the other examples.

However, there does seem to be an exuberant number of ip2long()s and long2ip()s in there.  The rangeToCIDRList() function starts by converting dotted decimal IP numbers to long integers, then converts them back to dotted decimals to pass along, which each receiving function promptly converts into long integers.  Is all that converting really necessary?  According to my investigations:  Nope.

class CIDR {
public static function countSetbits($int){
	$int = $int - (($int >> 1) & 0x55555555);
	$int = ($int & 0x33333333) + (($int >> 2) & 0x33333333);
	return (($int + ($int >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
	}

public static function validNetMask($netmask){
/*****	$netmask = ip2long($netmask); remove this line */
	$neg = ((~(int)$netmask) & 0xFFFFFFFF);
	return (($neg + 1) & $neg) === 0;
	}

public static function maskToCIDR($netmask){
	if(self::validNetMask($netmask))
/*****		return self::countSetBits(ip2long($netmask)); remove */
		return self::countSetBits($netmask); //replaces line above
	else
		throw new Exception('Invalid Netmask');
	}

public static function maxBlock($ipinput) {
/*****	return self::maskToCIDR(long2ip(-(ip2long($ipinput) & -(ip2long($ipinput))))); remove */
	return self::maskToCIDR(-($ipinput & -$ipinput)); //replaces line above
	}

public static function rangeToCIDRList($startIPinput,$endIPinput) {
	$start = ip2long($startIPinput);
	$end = ip2long($endIPinput);
	while($end >= $start) {
/*****		$maxsize = self::maxBlock(long2ip($start)); remove */
		$maxsize = self::maxBlock($start); //replaces line above
		$maxdiff = 32 - intval(log($end - $start + 1) / log(2));
		$size = ($maxsize > $maxdiff) ? $maxsize : $maxdiff;
		$listCIDRs[] = long2ip($start) . "/$size";
		$start += pow(2, (32 - $size));
		}
	return $listCIDRs;
	}
}

That saves like four ip2long()s and two long2ip()s each iteration. It don't get no better than that in my book.

Still testing… 

MikeSoja - April 27, 2011 -- 11:16 am    Filed in: Programming  
« This guy gets it
Knuckleheads »
As Happy As A Clam

Kayak2U.com

msoja RSS 2.0

Other's Pages









Search

Archive

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  


  • Books4Sale



    Soja's GoodReads Books4Sale Cheap

  • Category Cloud


  • Tag Cloud