Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

ipv4

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?

like image 353
planetp Avatar asked Feb 17 '10 10:02

planetp


People also ask

How do you express a range of IP addresses?

CIDR notation is written as the IP address, a slash, and the CIDR suffix (for example, the IPv4 " 10.2. 3.41/24 " or IPv6 " a3:bc00::/24 "). The CIDR suffix is the number of starting digits every IP address in the range have in common when written in binary. For example: " 10.10.

What is the range of all IP addresses?

IP addresses are expressed as a set of four numbers — an example address might be 192.158.1.38. Each number in the set can range from 0 to 255. So, the full IP addressing range goes from 0.0.0.0 to 255.255.255.255.


1 Answers

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.

like image 192
rjh Avatar answered Sep 28 '22 06:09

rjh