views:

615

answers:

7

What regex can I use to match any valid IP-address represented in dot-decimal notation?

+12  A: 

CPAN is your friend: Regex::Common or Net::IP::Match::Regexp.

bjelli
+1 : CPAN IS always your friend for Perl related question.
David Brunelle
+1  A: 

For IPv4 in an A.B.C.D (decimal) format, as a one-liner:

(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])

If nothing follows the address on the line, it can be contracted to:

(?:(?:[01]?\d?\d?|2[0-4]\d|25[0-5])(?:\.|$)){4}

Have fun.

vladr
inet_aton typically handles a lot more formats than just "A.B.C.D", try "ping 10.4" or "ping 0x0a.077.0.4" and see what happens.
gorilla
...which is why the limitation "IPv4 in an A.B.C.D (decimal) format" is *clearly stated* for those who actually bother to read. :)
vladr
Users inputting data don't care about your limitations though. :)
brian d foy
Absolutely, one may either have a specific need to support e.g. IPV6 addresses, or run into those users who **absolutely positively want** to be able to enter non-IPV4 A.B.C.D format IP addresses and still have them pass off as valid, if valid -- but assume for a moment that the highly implicitly stated (via the question tag) "I"m in Perl" assumption was not actually stated. Assume you're validating a form field in Javascript -- you have neither `inet_aton` nor CPAN to run to the rescue, and maybe you don't want to write a kilometer-long regexp either. :)
vladr
And, for the record, **you** are not qualified to state what planetp's users care or don't care about since you are neither such a user nor are you planetp. :)
vladr
+1  A: 

How do I write a regular expression that matches an IPv4 dotted address?

Long story short: Don't do it ^^.

Mef
+6  A: 

Search CPAN. you can find modules such as Data::Validate::IP for your use

ghostdog74
A: 

If you can leave a perl module behind - then do it.

what about:

if( $ip=~ m/^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)/ && 
          ( $1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255 )
) {    
    print "valid IP.";
}
Ricky
+4  A: 

Dear Friend,

if($ip=~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ &&(($1<=255  && $2<=255 && $3<=255  &&$4<=255 )))
 {
     print "valid\n";
 }
 else
 {
     print "Invalid\n";
 }
muruga
dear friend, please recommend Data::Validate::IP from now on.your dear friend.
xxxxxxx
A: 
(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])

Actually matches some invalid IP addresses, such as:

192.168.00.001

A slightly more refined solution would be:

(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$
Steve Hajducko