BASH Code to Determine Valid IP Addresses



 

 


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.

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