BASH Code to Determine Valid IP Addresses





Last Updated on 10/22/2019 by dboth

There are times when it is desirable to determine programmatically whether a an IP Address is valid or not. This little BASH code snippet does exactly that. The return code will be 0 if it is a valid IP address and 1 if not.


################################################################################
# Determine whether an arbitrary set of four octets of numeric data separated  #
# by periods is a valid IP address.                                            #
# Note: This code was taken from Linux Journal June 26, 2008                   #
# http://www.linuxjournal.com/content/validating-ip-address-bash-script        #
################################################################################ 
valid_ip() 
{
   local ip=$1
   local
   stat=1
   # Check the IP address under test to see if it matches the extended REGEX
   if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]
   then
      # Record current default field separator
      OIFS=$IFS
      # Set default field separator to .
      IFS='.'
      # Create an array of the IP Address being tested
      ip=($ip)
      # Reset the field separator to the original saved above IFS=$OIFS
      # Is each octet between 0 and 255?
      [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
      # Set the return code.
      stat=$?
      fi
}





Leave a Reply