smith
smith

Reputation: 3282

Regular expression to check if IP is found on 2 ranges

Is it possible to write a regular expression as one expression to check if an IP is found on 2 ranges?

I can do this in 2 steps:

if ($ip =~ /$range1/ and $ip =~ /$range2/ ) {
    print "intersection"
}

but I wonder if it's possible to do this in one regex:

if ($ip =~ /$my_regex/ ) {
    print "intersection";
}

Upvotes: 1

Views: 127

Answers (3)

Miller
Miller

Reputation: 35208

Yes, it is possible to join two independent subexpressions into a single regex using lookahead assertions:

if ($ip =~ /^(?=.*$range1)(?=.*$range2)/s ) {
    print "intersection"
}

However, if you really are dealing with IP addresses, you should use a module like NetAddr::IP.

Upvotes: 0

Chankey Pathak
Chankey Pathak

Reputation: 21676

Below is a solution in Perl.

Why not use NetAddr::IP and let it handle the thing? For example

#!/usr/bin/perl
use strict;
use warnings;
use NetAddr::IP;
my @addresses = (
    new NetAddr::IP '216.239.32.0/255.255.32.0',
    new NetAddr::IP '64.157.227.255/255.255.252.0'
);
my $banned = 0;
my $visitor_address = NetAddr::IP->new($visitor_ip);
foreach my $banned_address (@addresses) {
    if ($visitor_address->within $banned_address) {
       $banned = 1;
       last;
    }
}

Read the documentation and available methods at: https://metacpan.org/pod/NetAddr::IP

Upvotes: 2

user1558455
user1558455

Reputation:

You can use the Module NetAddr::IP:

use strict;
use warnings;
use NetAddr::IP;

my @addresses = (
    NetAddr::IP->new('192.168.172.1/255.255.0.0'),
    NetAddr::IP->new('10.1.0.0/255.0.0.0'),
);

my $address_to_check = NetAddr::IP->new($IP_TO_CHECK);

foreach my $address_in_list (@addresses) {
  if ($address_to_check->within $address_in_list) {
    # do something
  }
}

Upvotes: 3

Related Questions