How can I generate a range of IP addresses in Perl?

planetp picture planetp · Feb 17, 2010 · Viewed 7.5k times · Source

I need to generate a list of IP-addresses (IPv4) in Perl. I have start and end addresses, for example 1.1.1.1 and 1.10.20.30. How can I print all the addresses inbetween?

Answer

rjh picture rjh · Feb 17, 2010

Use Net::IP. From the CPAN documentation:

my $ip = new Net::IP ('195.45.6.7 - 195.45.6.19') || die;
# Loop
do {
    print $ip->ip(), "\n";
} while (++$ip);

This approach is more flexible because Net::IP accepts CIDR notation e.g. 193.0.1/24 and also supports IPv6.

Edit: if you are working with netblocks specifically, you might investigate Net::Netmask.