Warning: preg_replace(): Compilation failed: escape sequence is invalid in character class at offset 4 in /home/customer/www/theunixtips.com/public_html/wp-content/plugins/resume-builder/includes/class.resume-builder-enqueues.php on line 59

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. or explicit start and end addresses (e.g. or even with network mask (e.g. mask Following example shows all of these possible cases.


use NetAddr::IP;

my $ipAddr  = "";
my $netAddr = ""; # -

my $network  = NetAddr::IP->new($netAddr);
#my $network  = NetAddr::IP->new("", "");
#my $network  = NetAddr::IP->new("", "29");
#my $network  = NetAddr::IP->new("");
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).

1 Comment

Comments are closed.