in reply to Iterating through all IP addresses in a CIDR

In the spirit of there is more than one way to do it, here is my solution to the problem without using any of the CPAN modules. Just straight forward divide and conquer.

use strict; chomp(my @CIDR = <DATA>); foreach (@CIDR) { if (/\//) { # expand the address list my ($base, $range) = /(\d+\.\d+\.\d+\.)(.*)/; my ($r0, $r1) = split /\//, $range; if ($r1 < $r0) { die "invalid ip range" if length($r1) >= length($r0); $r1 = substr($r0, 0, length($r0) - length($r1)) . $r1; } print "$base$_\n" for $r0 .. $r1; } elsif (/-/) { my ($base, $from, $to) = /(\d+\.\d+\.\d+\.)(\d+)-\d+\.\d+\.\d+\.(\ +d+)/; print "$base$_\n" for $from .. $to; } else { # singular IP address print "$_\n"; } } __DATA__ 192.168.0.1 172.18.0.0/5 172.19.1.0/4 172.20.2.0/8 172.21.3.128/130 100.0.0.1-100.0.0.3 172.21.3.128/110
And the output (last entry has incorrect range) -
192.168.0.1 172.18.0.0 172.18.0.1 172.18.0.2 172.18.0.3 172.18.0.4 172.18.0.5 172.19.1.0 172.19.1.1 172.19.1.2 172.19.1.3 172.19.1.4 172.20.2.0 172.20.2.1 172.20.2.2 172.20.2.3 172.20.2.4 172.20.2.5 172.20.2.6 172.20.2.7 172.20.2.8 172.21.3.128 172.21.3.129 172.21.3.130 100.0.0.1 100.0.0.2 100.0.0.3 invalid ip range at p20.pl line 12, <DATA> line 7.
Update: added simple IP - IP processing for smackdab.