Home: Perl Programming Help: Regular Expressions:
Extracting an IPv4 address from line

New User

Jul 5, 2011, 2:01 PM

Views: 6097
Extracting an IPv4 address from line

Hi All,

I'm wondering what I should do to extract the second IP address from a log file I have. My log file looks like:

[03072011 13:32:01] connection connection.c:3880-message: connection 0x8fa0fe0 accept/tcp/none [>] state: none->established

I only want to snag the address Currently I'm using the following function to narrow it down but it doesn't seem to be working. Any pointers!?

##Loop to extract the ips 
my ($selected) = $_;
if ($selected =~ m/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/)
my $ip = $1 << 24 | $2 << 16 | $3 << 8 | $4;
print $ip;

Note @msg3880 is an array that holds all the lines above. Any help would be appreciated!


Jul 5, 2011, 8:53 PM

Views: 6087
Re: [mant1s] Extracting an IPv4 address from line

You are looking for the address at the start of the line. It is not there so no match. Replace "^" with "->" to look for the address immediately after the "arrow".

Perl's bit-wise OR ("|") probably does not do what you expect. Refer to the paragraph "Bitwise Or and Exclusive Or" (and its rererences) in perldoc perlop.
Good Luck,


Jul 7, 2011, 3:07 PM

Views: 6037
Re: [mant1s] Extracting an IPv4 address from line

use Regexp::Common qw(net);

- Miller