in reply to validateMask

Code below shows my minor tweaks, idnopheq, to your neat snippet.

Line 12 rejects $mask if any octet(s) are other than 1 to 3 digits.   Somewhat redundant, since you already check for > 255 at line 20.

Line 22y3 allows the sub to pass the valid octet of 252, which happens to not be divisable by 8.   Although you may have left that out on purpose, since a 30bit mask would normally be used only with point-to-point WAN links.

I've not used them yet myself, but modules like Net::Netmask, Net::IPv4Addr, Network::IPv4Addr, NetAddr::IP, and Tie::NetAddr::IP might be worth looking at.
    cheers,
    Don
    striving toward Perl Adept
    (it's pronounced "why-bick")

1: # sub validateMask 2: # 3: # takes a dotted-decimal IP mask 4: # 5: # returns 1 if the mask is valid 6: # returns undef if not 7: # 8: 9: sub validateMask { 10: my $mask = shift; 11: my $net = 0; 12: return 12: unless $mask =~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; 12y: # accept only 1 to 3 digit octe +ts in above regex 14: foreach ( split ( /\./, $mask ) ) { 15: if ( 16: $net == 1 17: && 18: $_ != 0 19: ) { return; } 20: if ( $_ > 255 ) { return; } 21: if ( $_ == 255 ) { next; } 22: if ( 22y1: $_ % 8 != 0 # if an octet mod 8 isn't 0, + bad mask 22y2: && 22y3: $_ != 252 # 255 is valid octet, but oc +tet mod 8 isn't 0 22y4: ) { return; } 23: $net = 1; 24: next; 25: } 26: return 1; 27: }

Replies are listed 'Best First'.
Re: Re: validateMask (regex tweak, 30bit mask, CPAN modules)
by idnopheq (Chaplain) on May 09, 2001 at 18:51 UTC
    THX for the comments ... I rewrote the validateMask sub, including your

    return unless $mask =~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;

    My new version is far simpler than my original post, using Socket, unpack, and join to give a 32 character binary string, then searching for the pattern /01/. If we find it, bad mask. Everything else then must be good ( unless someone finds a fatal flaw here, too! :b ).

    I wasn't initially that excited about requiring Socket, but then I figured this will likely be used (if at all) in a networking script, so Socket.pm is ok.


    --
    idnopheq
    Apply yourself to new problems without preparation, develop confidence in your ability to to meet situations as they arrise.