Jason Block
Jason Block

Reputation: 165

Adding IP addresses in Perl?

Let's say I have arguments to a function "start_ip_address", "ip_address_increment", and "number_of_increment".

I would like to print the start_ip_address, and then that address incremented by the increment, number_of_increment times.

So if "start_ip_address" = 192.168.0.0 and "ip_address_increment" = 0.0.1.1 and "number_of_increment" = 3, I'd like to print:

192.168.0.0

192.168.1.1

192.168.2.2

192.168.3.3

How can I do this? I'm pretty bad with Perl string manipulation.

Upvotes: 0

Views: 941

Answers (1)

ikegami
ikegami

Reputation: 386561

IPv4 addresses are just 32-bit integers. Each number represents a byte.

sub to_num { unpack 'N', pack 'C4', split /\./, $_[0] }
sub fr_num { join '.', unpack 'C4', pack 'N', $_[0] }

my $ip = to_num($start_ip_address);
my $inc = to_num($ip_address_increment);

say fr_num($ip);
for (1..$number_of_increments) {
   $ip += $inc;
   say fr_num($ip);
}

Upvotes: 3

Related Questions