Noosrep Noosrep - 1 month ago 5
Perl Question

Loop over a range of IPs with perl IP library

I'm trying to create an IP table list where I can see which IPs are in use and which aren't.

I use the

Net::IP
library for this. Code snippet:

my @IPsinrange = &getAllIPs($range) ; #range is x.x.x.x/subnet format
sub getAllIPs {
my $ip = new Net::IP ($range) || die;
my @IPs ;
# Loop
do {
push @IPs, $ip->ip() ;
} while (++$ip);

return @IPs ;
}


This works for a x.x.x.0/24 network and this works for 1.2.3.4/32 but when I use 1.2.3.4/29 for instance, the loop just dies. I thought it could be because of the fact that there were no IP adresses in use, but there are 4 IPs in that range that are alive.

Answer

The reason this isn't working is due to the fact that the module requires you to send in a proper network address as the starting point of a given IP prefix.

Since you want to use a /29 prefix, valid ranges would be:

1.2.3.0/29
1.2.3.8/29
1.2.3.16/29
...etc

As mentioned in the comments, the documentation states that the proper usage of the constructor to get proper diagnostic output is:

$ip = new Net::IP ('1.2.3.0/29') or die (Net::IP::Error());
Comments