如何检查IP地址是否在perl的特定范围内?

时间:2014-07-23 16:48:30

标签: perl ip cgi ip-address

我在perl中编写CGI脚本。 如何检查是否有IP地址,例如124.21.23.5,是否在100.0.0.0 - 200.79.255.255范围内?

我获取IP地址的方式是:

    my $ip = $ENV{'REMOTE_ADDR'};

1 个答案:

答案 0 :(得分:6)

使用Net::IPoverlaps方法:

use strict;
use warnings;

use Net::IP;

my $range = Net::IP->new('100.0.0.0 - 200.79.255.255') or die Net::IP::Error();

while (<DATA>) {
    chomp;
    my $ip = Net::IP->new($_) or die Net::IP::Error();
    my $match =  $range->overlaps($ip) ? "(match)" : "";
    print "$_ $match\n";
}

__DATA__
10.0.0.1
99.99.99.99
100.0.0.1
124.21.23.5
200.79.255.1
200.80.1.1

输出:

10.0.0.1
99.99.99.99
100.0.0.1 (match)
124.21.23.5 (match)
200.79.255.1 (match)
200.80.1.1