Parsing tcpdump logs with PHP


I’m working on parsing this file with PHP and regex:

19:28:39.409202 IP > Flags [.], ack 3074814080, win 501, options [nop,nop,TS val 94559087 ecr 3035083725], length 0

I’d like to the data from it like so:

["", "http"]

How could I do this? I’m a novice when it comes to regex.

The key is usually identifying what doesnt change in a string, and keying off of that.

So, let’s start assuming things, and then see whether we actually need regex (hint, probably not.)

1: A line is separated by spaces.
2: The target values will always be in the third and fifth of these ‘words’.
3: the IP is always an IPv4 address, followed by the port.

Step 1: explode the string on spaces. (don’t include empty strings in your result!)
Step 2: explode the third chunk of that explosion on the period. Slice the first four elements back together with periods; there’s your origin IP.
Step 3: explode the fifth chunk of the original explosion. Pop the last thing off the end of the resultant array; there’s your port.
Step 4: Take the result of step 2, and the result of step 3, and put them in an array.

Now, could you do it with regex? Yes. If you’re very keen on using it, you could look for strings that are 4 sets of digits with periods between them followed by another period and capture both that and the non-space characters that follow the last period. You’d end up with two records for each subpattern, and you’d take the first instance of the first subpattern, and the second instance of the second subpattern.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.