How to verify IPv4 address

There is a large number of different ways to verify IPv4 address inside a shell script, but many of these are complicated or incomplete. I will describe a simple and verbose way to check IPv4 address using ipcalc utility.

Install required software

Install ipcalc utility.

$ sudo apt-get install ipcalc

Check IPv4 address inside terminal

Check 84.16.240.28 IPv4 address.

$ ipcalc 84.16.240.28 | \
  awk 'BEGIN{FS=":"; is_invalid=0} /^INVALID/ {is_invalid=1; print $1} END{exit is_invalid}'

It is a valid IPv4 address.

$ echo $?
0

Check 84.16.240.328 IPv4 address.

$ ipcalc 84.16.240.328 | \
  awk 'BEGIN{FS=":"; is_invalid=0} /^INVALID/ {is_invalid=1; print $1} END{exit is_invalid}'
INVALID ADDRESS

This is an invalid IPv4 address.

$ echo $?
1

Check 84.16.240.28/226 IPv4 address.

$ ipcalc  84.16.240.28/226 | \
  awk 'BEGIN{FS=":"; is_invalid=0} /^INVALID/ {is_invalid=1; print $1} END{exit is_invalid}'
INVALID MASK1

This IPv4 address is not valid due to invalid network mask.

$ echo $?
1

Check 84.16.240.328/226 IPv4 address.

$ ipcalc  84.16.240.328/226 | \
  awk 'BEGIN{FS=":"; is_invalid=0} /^INVALID/ {is_invalid=1; print $1} END{exit is_invalid}'
INVALID ADDRESS
INVALID MASK1

This is an invalid IPv4 address with invalid network mask.

$ echo $?
1

Check IPv4 address inside shell script

Function used to check IPv4 address.

check_ipv4_address() {
  if [ -n "$1" -a -z "${*##*\.*}" ]; then
    ipcalc $1 | \
      awk 'BEGIN{FS=":";is_invalid=0} /^INVALID/ {is_invalid=1; print $1} END{exit is_invalid}'
  else
    echo "EMPTY OR INVALID ADDRESS"
    return 125
  fi
}

Shell script using the above-mentioned function.

#!/bin/bash
# Check IPv4 address

# function to check IPv4 address
check_ipv4_address() {
  if [ -n "$1" -a -z "${*##*\.*}" ]; then
    ipcalc $1 | \
      awk 'BEGIN{FS=":";is_invalid=0} /^INVALID/ {is_invalid=1; print $1} END{exit is_invalid}'
  else
    echo "EMPTY OR INVALID ADDRESS"
    return 125
  fi
}

# shell script requires exactly one parameter
if [ "$#" -ne "1" ]; then
  exit
fi

# param
parameter="$1"

# function output and exit code
check_output=$(check_ipv4_address $parameter)
check_exit_code=$(echo $?)

if [ "$check_exit_code" -eq "0" ]; then
  echo "IPv4 address is valid"
else
  echo "IPv4 address is invalid"
  echo $check_output
fi

Sample output.

$ check_ipv4.sh 8.8.8.8
IPv4 address is valid
$ check_ipv4.sh 8.8.4.444
IPv4 address is invalid
INVALID ADDRESS

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.