#!/bin/bash

# Get the output of ifconfig and grep the IP address line
ip_info=$(ifconfig eth0 | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*')

# Separate the string by the delimiter ':'
IFS=':' read -ra ADDR <<< "$ip_info"

# Extract the potential IP address
if [ "${#ADDR[@]}" -eq 2 ]; then
    ip="${ADDR[1]}"
else
    ip="${ADDR[0]}"
fi

# Trim whitespace from the IP address
ip=$(echo "$ip" | xargs)

# Function to check if an IP address is valid
function valid_ip() {
    local ip=$1
    local stat=1

    if [[ $ip =~ ^([0-9]{1,3}\.){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
}

# Check if the extracted string is a valid IP address
if valid_ip "$ip"; then
    echo "$ip"
 else
    echo "NOT_VALID"
fi
