Originally published December 11, 2016 @ 11:08 pm

This is a small collection of tools and examples for working with IP addresses and ranges in Bash. This post is not meant to be a complete reference, rather a practical how-to guide.

The basic IP regex looks something like this:

grep -oE "([0-9]{1,3}\.){3}([0-9]{1,3})"

This will match an IP address or something that looks a lot like it. If you want only valid IP addresses, the regex becomes a bit longer:

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

You can find more examples here. A very useful utility is cidr2regex – a Python script that will convert CIDR notation to a Python-compatible regex. It will not be the prettiest or most efficient regex, but it will get the job done right. Here’s an example:

# echo "" | cidr2regex

Another helpful utility is grepcidr. To install from source:

cd /tmp ; wget http://www.pc-tools.net/files/unix/grepcidr-2.0.tar.gz ; tar xvfz grepcidr-2.0.tar.gz ; cd grepcidr-2.0/ ; make && make install ; which grepcidr


# grepcidr -v "" /var/log/secure | grep -vc

The ipcalc is a simple but helpful utility for, say, configuring NICs. Here’s a quick example:

# ipcalc -bmnps

A similar but better tool is sipcalc (yum install sipcalc):

# sipcalc
-[ipv4 :] - 0

Host address            -
Host address (decimal)  - 3232266752
Host address (hex)      - C0A87A00
Network address         -
Network mask            -
Network mask (bits)     - 26
Network mask (hex)      - FFFFFFC0
Broadcast address       -
Cisco wildcard          -
Addresses in network    - 64
Network range           - -
Usable range            - -

Here are a few examples of generating various IP ranges (useful for firewall configurations, blacklists, etc).

Using seq:

# seq -f "192.168.122.%g" 40 43

Using bash brace expansion:

# printf "%s\n" 192.168.122.{40..43}