Home > perl, Programming > Extract ip address(es) from standard input using perl and regular expression

Extract ip address(es) from standard input using perl and regular expression

Method 1:

$ cat file | perl -nle 'print "$1" if
/(?!0+\.0+\.0+\.0+$)(([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5]))/'


Method 2:

$ cat file | perl -nle 'print $1 if /(([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+))/g && $2<256 && $3<256 && $4<256 && $5<256'

I prefer using method 2 because it’s simpler to construct and for ip addresses such as 1.2.3.1234 (obvious an invalid one), using method 1 results in1.2.3.123 being matched. But method 2 will not mistakingly pick up that ip address.

Reference: Mastering Regular Expressions by Jeffrey E.F. Friedl.

Advertisements
Categories: perl, Programming
  1. Clif Bratcher
    December 15, 2009 at 8:04 pm

    I’d highly recommend *against* using regular expressions to validate IPv4 addresses (and even more so v6). You end up with a massive amount of edge cases like the one you pointed out with your first method.

    Take a look into NetAddr::IP. It’s a robust, yet easy to use IP utility.

    Assuming each IP is on a single line, this is equivalent to what I think you’re trying to do:
    “perl -MNetAddr::IP -lne ‘print if NetAddr::IP->new($_)’ file”

    Which has the added benefit of supporting v6, or even parsing cidr prefixes, ala “perl -MNetAddr::IP -lne ‘$ip = NetAddr::IP->new($_); print $ip if $ip’ file”

    http://www.perlmonks.org/?node_id=221512

  2. ricoch3n
    December 15, 2009 at 11:39 pm

    Using NetAddr::IP is indeed much neater but this module is not installed by default on some systems ( LinuxMint for example ), so when adding NetAddr::IP to the system is not possible I’ll use the regular expression approach as a backup. Thanks for bringing this up.

  1. March 28, 2011 at 8:54 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: