http://qs321.pair.com?node_id=304489


in reply to Iterating through all IP addresses in a CIDR

Heres a nifty line to compute number of addresses based on the CIDR.

my $cidr = 24; my $ips = 1 << (32 - $cidr); # alternately if your block is a /24 or larger (more IPS) # then you could do my $networks = (1 << (32 - $cidr)) / 256; # /24 == 1 # /23 == 2 etc..

Just remember that the first snippet is the total number of IPs in the block, not actual usable. There are all sorts of fun ways to play with this. The logic gets a little tricky based on the smaller blocks, and determining if a network address for the block is on a valid boundary, but its certainly doable. Also module use for this kind of work is a GoodThing(TM). I ended up going through the pains of figuring it all out recently, as I thought the code was going to be semi-throwaway.

use perl;