Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if an ip address is in a specific range in perl?

I'm writing a CGI script in perl. How do I check if an ip address, e.g. 124.21.23.5, is in the range 100.0.0.0 - 200.79.255.255 ?

The way I get the ip address is:

    my $ip = $ENV{'REMOTE_ADDR'};
like image 249
user3063285 Avatar asked Sep 04 '25 16:09

user3063285


1 Answers

Using Net::IP and the overlaps method:

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

Outputs:

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
like image 187
Miller Avatar answered Sep 07 '25 19:09

Miller