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 "192.168.122.0/26" | cidr2regex
^192.168.122.(5\d|4\d|3\d|2\d|1\d|\d|6[0-3])$

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

Example:

# grepcidr -v "192.168.0.0/16" /var/log/secure | grep -vc 127.0.0.1
11

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

# ipcalc -bmnps 192.168.122.0/26
NETMASK=255.255.255.192
PREFIX=26
BROADCAST=192.168.122.63
NETWORK=192.168.122.0

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

# sipcalc 192.168.122.0/26
-[ipv4 : 192.168.122.0/26] - 0

[CIDR]
Host address            - 192.168.122.0
Host address (decimal)  - 3232266752
Host address (hex)      - C0A87A00
Network address         - 192.168.122.0
Network mask            - 255.255.255.192
Network mask (bits)     - 26
Network mask (hex)      - FFFFFFC0
Broadcast address       - 192.168.122.63
Cisco wildcard          - 0.0.0.63
Addresses in network    - 64
Network range           - 192.168.122.0 - 192.168.122.63
Usable range            - 192.168.122.1 - 192.168.122.62

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
192.168.122.40
192.168.122.41
192.168.122.42
192.168.122.43

Using bash brace expansion:

# printf "%s\n" 192.168.122.{40..43}
192.168.122.40
192.168.122.41
192.168.122.42
192.168.122.43