What regex can I use to match any valid IP-address represented in dot-decimal notation?
views:
615answers:
7+1 : CPAN IS always your friend for Perl related question.
David Brunelle
2010-03-16 13:56:09
+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
2010-02-27 09:52:32
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
2010-02-27 11:41:24
...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
2010-02-27 20:26:13
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
2010-03-16 17:45:47
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
2010-03-16 23:22:52
+1
A:
How do I write a regular expression that matches an IPv4 dotted address?
Long story short: Don't do it ^^.
Mef
2010-02-27 09:52:43
+6
A:
Search CPAN. you can find modules such as Data::Validate::IP for your use
ghostdog74
2010-02-27 10:29:13
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
2010-02-27 11:34:48
+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
2010-03-01 10:40:18
dear friend, please recommend Data::Validate::IP from now on.your dear friend.
xxxxxxx
2010-03-10 07:47:30
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
2010-05-24 17:54:44