How can I parse IP addresses and address ranges using Perl?

I have a list of IP addresses:


238.51.208.96/28
238.51.209.180-199
238.51.209.100-109
238.51.213.2-254
...


How can I easily parse them? I need the first and last IP from the range. For the first line I can use the CPAN module Net :: Netmask, but what to do with other lines?

+5
source share
2 answers

Try Net :: IP module

If other templates are not supported, you may need to make some changes to ips in achievements, for example

238.51.209.180-199

to

238.51.209.180 - 238.51.209.199

using some regular expression like

$range =~ s/^((?:\d+\.){3})(\d+)-(\d+)$/$1$2 - $1$3/gm;

script:

use warnings;
use strict;
use Net::IP;
my $range = "238.51.209.180-199";
$range =~ s/^((?:\d+\.){3})(\d+)-(\d+)$/$1$2 - $1$3/;
my $ip = new Net::IP ($range) || die;
print $ip->ip (), "\n";
print $ip->last_ip (), "\n";
+4

All Articles