Short little function, Takes 2 IP and compares them - returning true or false. Also takes a CIDR netblock and an IP and returns true if the IP is within the netblock.
# Quick example print (ip_comp("192.168.3.0/16","192.168.2.5")?"MATCH":"NO-MATCH"); sub ip_comp { my ($n, $i) = @_; # $n - the "network ip" # x.x.x.x or x.x.x.x/c # where x is 0-255 and c is the CIDR netblock # $i is the ip we want to check return ($i eq $n) unless $n =~ /^(.*)\/(.*)$/; return (((unpack('N',pack('C4',split(/\./,$i))) ^ unpack('N',pack('C4' +,split(/\./,$1)))) & (0xFFFFFFFF << (32 - $2))) == 0); }

Replies are listed 'Best First'.
Re: Check IP with support for CIDR
by ehdonhon (Curate) on Apr 11, 2002 at 12:21 UTC
(MeowChow) Re: Check IP with support for CIDR
by MeowChow (Vicar) on Apr 12, 2002 at 01:24 UTC
    You can simplify the CIDR mask check:
    return unpack ('N', pack ('C4', split /\./, $i) ^ pack ('C4', split /\ +./, $1)) >> 32 - $2;
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print
      Could not get that to work. However, it did make me think and hence this:
      return ( (unpack('N',pack('C4',split(/\./,$i))) ^ unpack('N',pack('C4' +,split(/\./,$1)))) >> (32-$2) ) == 0;
      --
      TTFN, FNORD
        My bad, I forgot to negate the result:
        return not unpack ('N', pack ('C4', split /\./, $i) ^ pack ('C4', spli +t /\./, $1)) >> 32 - $2;
           MeowChow                                   
                       s aamecha.s a..a\u$&owag.print