Available addresses

The scenario

You want to add a new server/VM/container to your network and you want to statically assign the address. But, you don’t keep records of what is where and which IP addresses are assigned.

The workaround

I have been just copying and pasting in a bash script to get the results of what IP addresses are available. It works but it isn’t super.

for i in {1..254}; do ping -c 1 -W 100 192.168.100.$i | grep 'time='; done

Something a bit better

I am usually working from my laptop when I am looking for a spare address within a range. So, I figured I could use a bash script that can be kept in the home directory and when it is run it will accept some a start and an end address. It takes those arguments and checks all of the IP addresses within. There is also some colouring to make it a bit more obvious which addresses are free and which are in use.

You will need to have nmap installed on your system/server for the script to work

#!/bin/bash
# ANSI color codes
# Green background and black text for available IP addresses
GREEN_BG='\033[42;30m'
# Red background for in-use IP addresses
RED_BG='\033[41m'
# No color (reset)
NC='\033[0m'
# Function to check if an IP address is reachable
check_ip() {
    local ip=$1
    if ping -c 1 -W 1 "$ip" &>/dev/null; then
        echo -e "${RED_BG} $ip is in use. ${NC}"
    else
        echo -e "${GREEN_BG} $ip is available. ${NC}"
    fi
}
# Input range in the format:  
read -p "Enter the starting IP address: " start_ip
read -p "Enter the ending IP address: " end_ip
# Extract the prefix from the starting IP address
prefix=$(echo "$start_ip" | cut -d '.' -f 1-3)
# Loop through the IP range and check availability
for ((i = $(echo "${start_ip}" | cut -d '.' -f 4); i <= $(echo "${end_ip}" | cut -d '.' -f 4); i++)); do
    ip_address="${prefix}.${i}"
    check_ip "$ip_address"
done
chmod +x ping_range.sh

Then you run it

./ping_range.sh

What it looks like

You will quickly see which IPs are available and which aren’t

It is pretty obvious which addresses are available for use 👍