简体   繁体   中英

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

I have list of IPs:

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 first and last IP from range. For the first line I can use Net::Netmask CPAN module, but what can I do with others lines?

Try Net::IP module

If second patterns does not support, you may need to some changes to ips in advances like

238.51.209.180-199

to

238.51.209.180 - 238.51.209.199

by using some regex, for example,

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

Full 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";

您可以使用Regexp :: Common :: net包来匹配IP地址,并使用CPAN上任意数量的模块(包括Network :: IPv4AddrNetAddr :: IPNet :: CIDR )来操纵它们(并获取网络掩码等)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM