Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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;


Comment on Re: Iterating through all IP addresses in a CIDR
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2014-10-02 14:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (61 votes), past polls