check if an IP is valid

I was tasked with crafting a Bash program designed to determine the validity of a supplied IP address and assess whether each octet falls within the acceptable range.


 #!/bin/bash


# Function to validate an IP address

is_valid_ip() {

    local ip="$1"

    local regex="^([0-9]{1,3}\.){3}[0-9]{1,3}$"

    

    if [[ $ip =~ $regex ]]; then

        # Check if each octet is in the valid range (0-255)

        IFS='.' read -r -a octets <<< "$ip"

        for octet in "${octets[@]}"; do

            if [[ "$octet" -lt 0 || "$octet" -gt 255 ]]; then

                return 1

            fi

        done

        return 0

    else

        return 1

    fi

}


# Read an IP address from the user

read -p "Enter an IP address: " input_ip


# Check if the provided IP address is valid

if is_valid_ip "$input_ip"; then

    echo "The IP address $input_ip is valid."

else

    echo "The IP address $input_ip is not valid."

fi

Comments

Popular posts from this blog

AWS: Auto Scaling

Jenkins Pipeline

EC2-Instances-awscli