perl : find if IP address is in Network range

Using NetAddr::IP one can find if a given IP address is in provided Network range or on the subnet. This can take many different representations of the subnet address. For example you can throw at it the CIDR (e.g. 192.168.1.0/29) or explicit start and end addresses (e.g. 192.168.1.0-192.168.1.7) or even with network mask (e.g. 192.168.1.0 mask 255.255.255.248). Following example shows all of these possible cases.

#!/usr/local/bin/perl

use NetAddr::IP;

my $ipAddr  = "192.168.1.8";
my $netAddr = "192.168.1.0/29"; # 192.168.1.0 - 192.168.1.7

my $network  = NetAddr::IP->new($netAddr);
#my $network  = NetAddr::IP->new("192.168.1.0", "255.255.255.248");
#my $network  = NetAddr::IP->new("192.168.1.0", "29");
#my $network  = NetAddr::IP->new("192.168.1.0-192.168.1.7");
my $ip = NetAddr::IP->new($ipAddr);

if ($ip->within($network)) {
        print $ip->addr() . " is in same subnetn";
}
else {
        print $ip->addr() . " is outside the subnetn";
}

There are multiple ways the input for network can be provided (four ways are shown above with 3 commented).

  • Marcello

    Great tip. Exactly what I was looking for..

  • Christian

    good post. works as expected