Skip to content

How to Validate IPv4 Addresses in Shell Script

Advertisement

Validating IP addresses is a common task in networking and system administration. In this tutorial, we’ll learn how to validate IPv4 addresses using a shell script. This is particularly useful in situations where you need to ensure that user input or data from another source is in the correct IPv4 format.

Understanding IPv4 Address Format

An IPv4 address consists of four octets, each ranging from 0 to 255, separated by dots. For example, 192.168.1.1 is a valid IPv4 address.

Prerequisites

  • Basic knowledge of shell scripting
  • Access to a Unix-like environment (e.g., Linux, macOS)

Bash Script to Validate IPv4 Address

Open your favorite text editor and start a new shell script file. We’ll use a function to validate the IPv4 address. This function uses regular expressions to check if the input matches the IPv4 pattern.


#!/bin/bash
# Filename: validate_ip.sh

validate_ip() {
    local ip=$1
    local stat=1

    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        OIFS=$IFS
        IFS='.'
        ip=($ip)
        IFS=$OIFS
        [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
        stat=$?
    fi

    return $stat
}

echo -n "Enter IPv4 address: "
read ip_address

if validate_ip $ip_address; then
    echo "${ip_address} is a valid IPv4 address."
else
    echo "${ip_address} is a invalid IPv4 address."
fi

Testing the Script

  1. Make the script executable: chmod +x validate_ip.sh
  2. Run the script: ./validate_ip.sh
  3. Enter an IPv4 address when prompted.

Conclusion

With this simple shell script, you can easily validate IPv4 addresses. This script can be integrated into larger projects or used standalone in network-related scripts.

Feel free to modify and expand this script according to your needs. For example, you might want to process multiple IP addresses from a file or include additional logging for invalid inputs.

Rahul

I, Rahul Kumar am the founder and chief editor of TecAdmin.net. I am a Red Hat Certified Engineer (RHCE) and working as an IT professional since 2009..

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top