What exactly do you consider valid? Is 241.57.97.2 valid (it's in an unassigned range)? What about 198.51.100.2 (it's reserved for documentation)? Are 6-to-4 IPv6 addresses to be considered valid IPv6 addresses?
–
GillesAug 28 '11 at 17:43

3 Answers
3

There are several usual notations for IPv4 and IPv6 addresses. Here's an extended regular expression, suitable for Perl m//x, that captures the usual notations. If you remove the comments and whitespace, you can use it with grep -E, awk, or any other utility that uses extended regular expressions (ERE).

...And you are not checking the range of values :)
–
rozcietrzewiaczAug 28 '11 at 18:40

@rozcietrzewiacz I'm not? I wrote this quickly and didn't test it, so I may have made a mistake. What bad value gets through? I've made the test a bit more precise and added a way to test the range for decimals.
–
GillesAug 28 '11 at 18:52

Oh, right - you are checking the range... Only you didn't add separators at the beginning and end, so things like 999.0.0.999 seem to pass.
–
rozcietrzewiaczAug 28 '11 at 18:54

I'd add [^0-9] at the beginning and the end of each...
–
rozcietrzewiaczAug 28 '11 at 19:01

You are incorrectly treating numbers with leading zeroes as decimal in dotted quads: POSIX (the relevant standard on a unix ) inet_ntoa specifies that in the “IPv4 dotted decimal notation”, despite its name, “a leading '0' implies octal”. And why don't you let me write ping 134744072? And what about IPv6?
–
GillesSep 28 '11 at 20:42

I simply have never, in seven years of professional development, seen anyone use anything other than dotted decimal for IPv4. I have, on the other hand, seen people confused that their 08 was interpreted as octal. I never said my code was complete, but it's simple and works for the canonical case.
–
l0b0Sep 29 '11 at 8:10