Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Iterate network hosts

by rob_au (Abbot)
on Mar 29, 2002 at 11:58 UTC ( [id://155226]=CUFP: print w/replies, xml ) Need Help??

Recently upon browsing through some of the code and snippets posted on Perlmonks, I came across a number of nodes which performed network administration tasks. I was however dismayed to find many of these nodes used hard-coded network address, iterating through each host address, in one case, as follows:

my $subnet = "40"; for(1..239){ chomp; my $ip = "10.1.$subnet.$_"; . . }

To my mind, there is a much better way to iterate through network hosts, namely, making use of the Net::Netmask module - The following subroutine of code uses this module to iterate through network hosts, the network determined by the network address and subnet mask passed as arguments to this subroutine. The network address and subnet mask passed to this subroutine can take the form of separate network block and subnet masks (eg. 192.168.1.0 and 255.255.255.0) or CIDR notation (eg. 192.168.1.0/24).

Never again should your network administration scripts be non-portable!

use Net::Netmask; sub ips { my $net = Net::Netmask->new(@_); wantarray ? $net->enumerate : \@{$net->enumerate}; }

Replies are listed 'Best First'.
•Re: Iterate network hosts
by merlyn (Sage) on Mar 29, 2002 at 14:23 UTC
    Maybe it's just the earliness of the day, but I had to read the title three times before I didn't read it as "irritate network hosts", and wondered why anyone would want to do that.

    {grin}

    -- Randal L. Schwartz, Perl hacker

      No fair, now I'm going to be reading 'Iterate' as 'Irritate' for far too long. Just hope I don't end up typing it that way.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-03-28 16:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found