in reply to IP Address Sanity

This bit of code is what I like to use to check the validity of an IP address.

This is a variation of one from the the Great Book "Mastering Regular Expressions" by Jeffrey Friedl,
which I highly recommend.

unless ( $ip =~ m/^(?:[1]?\d\d?|2[0-4]\d|25[0-5])\. (?:[1]?\d\d?|2[0-4]\d|25[0-5])\. (?:[1]?\d\d?|2[0-4]\d|25[0-5])\. (?:[1]?\d\d?|2[0-4]\d|25[0-5])$ /x ) { # do something }
This catches everything except for '0.0.0.0' ip's

which you can handle easily by one addtional check to your test routine.

if ( $ip =~ /^0.0.0.0$/ ) { # do something }
Best Regards,
Wonko

Replies are listed 'Best First'.
Re: Re: IP Address Sanity
by demerphq (Chancellor) on Dec 16, 2002 at 22:28 UTC
    Your pattern does match 0.0.0.0 from what I can tell. And this slight change makes it robust against arbitrary prefix zeros to boot.
    /^ 0*?(?:1?\d\d?|2[0-4]\d|25[0-5])\. 0*?(?:1?\d\d?|2[0-4]\d|25[0-5])\. 0*?(?:1?\d\d?|2[0-4]\d|25[0-5])\. 0*?(?:1?\d\d?|2[0-4]\d|25[0-5]) $/x;
    --- demerphq
    my friends call me, usually because I'm late....
      0.0.0.0

      is not actually a valid IP address. Which is why I mentioned that my pattern did not catch this (as invalid that is). The pattern matches it, but it should not. :-)

      Leading 0's in an IP are also considered to be invalid.

      1.003.003.123 is invalid and should be expressed without leading 0's

      Best Regards,
      Wonko

        This is all a matter of context - The IP address of 0.0.0.0 is indeed valid if dealing with network routes.

        Furthermore, the aspect of leading zeros is also contextual as an IP address is a 32-bit binary number, the dotted-quad merely a representation of this - It could be rightly argued that the leading zeros are nothing more than another representation of an IP address.

        See ybiC's Don't Use Regular Expressions To Parse IP Addresses! for an excellent treatise on this topic.

         

        perl -le 'print+unpack("N",pack("B32","00000000000000000000001000000111"))'