Noosrep Noosrep - 4 months ago 16
Perl Question

Find all IPs from subnet in perl

I have an IP with subnetmask and want to create a table in which every row is an IP.

Kind of like this:

IP | MAC | Alive
192.168.1.1 | ... | yes
192.168.1.2 | ... | no
192.168.1.3 | ... | yes
...


For a range with subnet /24, this is easy because I can generate a for loop from 0 to 254 but I'm having trouble with generating the table with a /21 subnet. Is there a way to find in perl what the minimum host, the maximum host and everything in between is?

I have checked the
Net::IP
and the
NetAddr::IP
module but don't seem a solution for my problem. However, I'm a perl newbie so it could be that I overlooked it.

edit:
found how to find first and last address:

my $range = "IP/subnet" ;
my $ip = new Net::IP ($range) || die;
print $ip->ip (), "\n";
print $ip->last_ip (), "\n";


Now I need to find the IPs in between

Mat Mat
Answer

The docs for Net::IP has an example for how to do this in the looping section.

Demo:

use Net::IP;

my $ip = new Net::IP("192.168.42.16/28");
do {
  print $ip->ip(), "\n";
} while (++$ip);
192.168.42.16
192.168.42.17
192.168.42.18
192.168.42.19
192.168.42.20
192.168.42.21
192.168.42.22
192.168.42.23
192.168.42.24
192.168.42.25
192.168.42.26
192.168.42.27
192.168.42.28
192.168.42.29
192.168.42.30
192.168.42.31