Linux: Grep IP addresses

I very often have to either find log entries related to a specific IP address or just find IP addresses in a log file or process a file containing IP addresses and other things. Here are a few commands I use for this.

First if you want to search for an IP address in a log file, you can just use grep:

grep 18.194.233.1 /var/log/auth.log

Unfortunately it might return more than expected: 118.194.233.1 and 18.194.233.14 also match. So we need to match 188.194.233.1 only using a whole word matching:

grep -w 18.194.233.1 /var/log/auth.log

Now if you want to search for lines containing IP addresses, you’ll need to use some regular expressions. An IP address is basically a dot separated sequence of 4 numbers each having 1 to 3 digits. So we can represent it this way:

grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' ...

If the IP addresses are stored alone on a line:

grep '^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$' ...

Of course if you have something like:

999.888.777.666

in your file, it will be matched although it is not a valid IP address (each part of the IP address cannot exceed 255). If you know you’ll never get such strings, then you can use the expression above otherwise:

Replace:

[0-9]\{1,3\}

By:

\(25[0-5]\|2[0-4][0-9]\|[01][0-9][0-9]\|[0-9][0-9]\)

So using:

grep '\(25[0-5]\|2[0-4][0-9]\|[01][0-9][0-9]\|[0-9][0-9]\)\.\(25[0-5]\|2[0-4][0-9]\|[01][0-9][0-9]\|[0-9][0-9]\)\.\(25[0-5]\|2[0-4][0-9]\|[01][0-9][0-9]\|[0-9][0-9]\)\.\(25[0-5]\|2[0-4][0-9]\|[01][0-9][0-9]\|[0-9][0-9]\)' ...

If you do not want to allow IP address containing e.g. 001 instead of 1, you can replace the expression above:

\(25[0-5]\|2[0-4][0-9]\|[01][0-9][0-9]\|[0-9][0-9]\)

By:

\(25[0-5]\|2[0-4][0-9]\|[1][0-9][0-9]\|[1-9][0-9]|[1-9]\)

3 thoughts on “Linux: Grep IP addresses

Leave a Reply

Your email address will not be published. Required fields are marked *