Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Iterating through all IP addresses in a CIDR

by l2kashe (Deacon)
on Nov 04, 2003 at 17:47 UTC ( #304489=note: print w/replies, xml ) Need Help??

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;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://304489]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (11)
As of 2016-10-21 17:16 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (289 votes). Check out past polls.