Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: generate range of IP address

by Zaxo (Archbishop)
on May 21, 2007 at 14:27 UTC ( [id://616570]=note: print w/replies, xml ) Need Help??


in reply to generate range of IP address

I hope you're permitted to use modules that ship with perl. Socket has what you need.

You should use numeric addresses instead of dotted quads for range calculations. That will save you fooling around with nested loops. Socket::inet_aton() and Socket::inet_ntoa() will convert between the two.

Update: Here is a shorty that prints the quads in a range of 2000 above a base address, omitting network addresses.

use Socket qw/inet_aton inet_ntoa/; my $base = '1.1.1.1'; my $nbase = unpack 'N',inet_aton($base); my @quads = map { inet_ntoa(pack('N', $_)) } grep { $_ % 256 } $nbase .. 2000 + $nbase; { local $, = ' '; print @quads, $/; }
To omit broadcast, too, you just need to and the grep condition with  ($_ % 256) != 255. Added unpack/pack to fix byte order for arithmetic. The numeric representation for inet_* is in network order.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: generate range of IP address
by Fletch (Bishop) on May 21, 2007 at 14:31 UTC

    I suggested as much in the CB but the OP persisted in wanting nested loops (hence the fish). Skipping network and/or broadcast addresses is a little trickier when you do it that way, though. Of course the simplest thing is to just install something like Net::Netmask and be done with it (or to just copy the guts into your source if you have to be moduleinstallaphobic for whatever reason; that also was suggested in the CB).

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2024-04-19 11:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found