Checking for available addresses

Checking for available addresses

Creating a bash script to show you what IP addresses are available for a given range

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.

1for 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

1#!/bin/bash
2
3# ANSI color codes
4# Green background and black text for available IP addresses
5GREEN_BG='\033[42;30m'
6# Red background for in-use IP addresses
7RED_BG='\033[41m'
8# No color (reset)
9NC='\033[0m'
10
11# Function to check if an IP address is reachable
12check_ip() {
13 local ip=$1
14 if ping -c 1 -W 1 "$ip" &>/dev/null; then
15 echo -e "${RED_BG} $ip is in use. ${NC}"
16 else
17 echo -e "${GREEN_BG} $ip is available. ${NC}"
18 fi
19}
20
21# Input range in the format: <starting_IP> <ending_IP>
22read -p "Enter the starting IP address: " start_ip
23read -p "Enter the ending IP address: " end_ip
24
25# Extract the prefix from the starting IP address
26prefix=$(echo "$start_ip" | cut -d '.' -f 1-3)
27
28# Loop through the IP range and check availability
29for ((i = $(echo "${start_ip}" | cut -d '.' -f 4); i <= $(echo "${end_ip}" | cut -d '.' -f 4); i++)); do
30 ip_address="${prefix}.${i}"
31 check_ip "$ip_address"
32done
1chmod +x ping_range.sh

Then you run it

1./ping_range.sh

What it looks like

ping_range.sh sample output
You will quickly see which IPs are available and which aren’t

It is pretty obvious which addresses are available for use 👍

Comments