SR has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I use the following regexp to validate the ip address

(((25[0-5])+|([2][0-4][0-9])|([0-1]?[0-9]{0,2}))\.){3}((25[0-5])+|([2][0-4][0-9])|([0-1]?[0-9]{0,2}))

I would like to know, is there any better way to do this??

Replies are listed 'Best First'.
Re: Validating IP Address
by NetWallah (Canon) on May 16, 2007 at 04:46 UTC
            is there any better way to do this??

    Yes there is : Use Regexp::Common

    use Regexp::Common qw /net/; /^$RE{net}{IPv4}$/; # Results in $1 .. $5 .. Please RTFM for details.

         "An undefined problem has an infinite number of solutions." - Robert A. Humphrey         "If you're not part of the solution, you're part of the precipitate." - Henry J. Tillman

Re: Validating IP Address
by laceytech (Pilgrim) on May 16, 2007 at 05:15 UTC
      In the OP's context, it may be valid to use a Regex to parse IP.

      Please see dws's response, in the discussion you referenced.

           "An undefined problem has an infinite number of solutions." - Robert A. Humphrey         "If you're not part of the solution, you're part of the precipitate." - Henry J. Tillman

Re: Validating IP Address
by f00li5h (Chaplain) on May 16, 2007 at 05:22 UTC

    Why not just connect to what you're given and see if it works? Then you can take IP6 addresses, random DNS names, things that appear in /etc/hosts but don't resolve via dns, hosts on NIS+.

    The world is your Soyster!

    @_=qw; ask f00li5h to appear and remain for a moment of pretend better than a lifetime;;s;;@_[map hex,split'',B204316D8C2A4516DE];;y/05/os/&print;

Re: Validating IP Address
by Wonko the sane (Curate) on May 16, 2007 at 12:21 UTC
    This is a variation of one from the 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 }
    Best Regards,
    Wonko