在Perl中,如何检查IP地址是否在特定范围内?

4

我正在使用Perl编写CGI脚本。

如何检查IP地址(例如124.21.23.5)是否在100.0.0.0 - 200.79.255.255范围内?

获取IP地址的方法如下:

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

1
你应该考虑使用Net::IP - AntonH
1
同意使用Net::IP。 - ouflak
1个回答

7
使用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接