Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Iterating through all IP addresses in a CIDR

by l2kashe (Deacon)
on Nov 04, 2003 at 17:47 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2024-04-19 01:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found