If you want to avoid the overhead of a full module, you could probably to it with two functions. First, something to convert IP addresses into integers, like:

sub ip_2_int { my ($ip) = @_; $ip =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/ or die "$ip is an invalid address"; return ($1<<24)|($2<<16)|($3<<8)|$4; }

Then, you just want to compare the network parts of the IP address with the network address. So, obviously you need to create the netmask (i.e., /16 is (2**16)-1, I think?), and then just compare the numbers, i.e.:

if (($ipaddress|$netmask)==$network) { # then $ipaddress is in the range $network/$netmask defines }

You could obviously wrap that in a common function, perhaps something like:

sub isInNetwork { my ($cidr_str, $ipaddress_str) = @_; my ($network_str, $netmask_str) = split ('/', $cidr_str); my ($network, $ip) = (ip_2_int ($network_str), ip_2_int ($ipaddress_str)); return ($network==($ip|(2**$network-1)); } print "10.0.50.12 is in 10/8!\n" if isInNetwork ('10.0.0.0/8', '10.0.50.12');

Or something (much more error checking would of course be required ;). That's off the bat, unfortunately I don't have access to a Perl right now :/ But, I'm pretty sure it's not supposed to be sufficiently complex to require a regex - remember, C programmers use IP addresses (socket.h), so it's can't be very difficult.


In reply to Re: regex for classless IP subnets by kal
in thread regex for classless IP subnets by permanentE

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.