in reply to Re: IPv4 regex
in thread IPv4 regex

I ran into undefined variables while iterating through a multidimensional hash containing all sort of server info using that function. I silenced them with a simple modification (checking if the parts of the IP is "defined"):
sub IP_valid { my $ip = shift; $ip =~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; foreach ($1,$2,$3,$4){ if ( defined $_ && $_ <256 && $_ >0) {next;} return 0; } return 1; }
Sure, that could have been added earlier but that if test was already checking multiple factors so it was easier to add. Thanks for this simple write-up! Just what I was looking for. Wow, 15 years later.

Replies are listed 'Best First'.
Re^3: IPv4 regex
by AnomalousMonk (Archbishop) on Jul 22, 2016 at 20:47 UTC

    Please also see Regexp::Common and Regexp::Common::net.

    c:\@Work\Perl\monks>perl -wMstrict -le "use Test::More 'no_plan'; use Test::NoWarnings; ;; VECTOR: for my $ar_vector ( [ '1.133.123.123', 1 ], [ '1.2.3.4', 1 ], [ '11.22.33.44', 1 ], [ '0.0.0.0', 1 ], [ '255.255.255.255', 1 ], [ '', '' ], [ '1asdf1.133.123.123', '' ], [ '12341.133.', '' ], [ '0.0.0.256', '' ], [ 'not at all valid', '' ], [ '1.2.3.4.5', '' ], [ '1111.2.3.1111', '' ], ) { my ($ip, $valid) = @$ar_vector; ;; my $status = $valid ? 'valid' : 'INVALID'; is IP_valid($ip), $valid, qq{'$ip' $status}; } ;; done_testing; ;; ;; use Regexp::Common qw(net); ;; sub IP_valid { my ($ip) = @_; return $ip =~ m{ \A $RE{net}{IPv4} \z }xms; } " ok 1 - '1.133.123.123' valid ok 2 - '1.2.3.4' valid ok 3 - '11.22.33.44' valid ok 4 - '0.0.0.0' valid ok 5 - '255.255.255.255' valid ok 6 - '' INVALID ok 7 - '1asdf1.133.123.123' INVALID ok 8 - '12341.133.' INVALID ok 9 - '0.0.0.256' INVALID ok 10 - 'not at all valid' INVALID ok 11 - '1.2.3.4.5' INVALID ok 12 - '1111.2.3.1111' INVALID 1..12 ok 13 - no warnings 1..13
    Note that, by design,  $RE{net}{IPv4} is not "anchored", so by itself it will match, e.g.:
    c:\@Work\Perl\monks>perl -wMstrict -le "use Regexp::Common qw(net); ;; print qq{matches IP of '$1'} if '99999.1.2.9999' =~ m{ ($RE{net}{IPv4}) }xms; " matches IP of '99.1.2.99'
    which may or may not be what you want. The  \A \z anchors in the example code above address this (quite intentional) feature.


    Give a man a fish:  <%-{-{-{-<