24/10/2018 Validating an IP Address in a Bash Script | Linux Journal
([Link]
(/)
HOW-TOs (/tag/how-tos)
Validating an IP Address in a Bash Script
by Mitch Frazier (/users/mitch-frazier) on June 26, 2008
I've recently written about using bash arrays (/node/1007118) and bash regular expressions
(/node/1006996), so here's a more useful example of using them to test IP addresses for validity.
To belabor the obvious: IP addresses are 32 bit values written as four numbers (the individual bytes of the
IP address) separated by dots (periods). Each of the four numbers has a valid range of 0 to 255.
The following bash script contains a bash function which returns true if it is passed a valid IP address and
false otherwise. In bash speak true means it exits with a zero status, anything else is false. The status of a
command/function is stored in the bash variable "$?".
[Link] 1/6
24/10/2018 Validating an IP Address in a Bash Script | Linux Journal
#!/bin/bash
# Test an IP address for validity:
# Usage:
# valid_ip IP_ADDRESS
# if [[ $? -eq 0 ]]; then echo good; else echo bad; fi
# OR
# if valid_ip IP_ADDRESS; then echo good; else echo bad; fi
#
function valid_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
}
# If run directly, execute some tests.
if [[ "$(basename $0 .sh)" == 'valid_ip' ]]; then
ips='
[Link]
a.b.c.d
[Link]
[Link]
[Link]
[Link]
[Link]
192.168.0
1234.123.123.123
'
for ip in $ips
do
if valid_ip $ip; then stat='good'; else stat='bad'; fi
printf "%-20s: %s\n" "$ip" "$stat"
done
fi
If you save this script as "valid_ip.sh" and then run it directly it will run some tests and prints the results:
[Link] 2/6
24/10/2018 Validating an IP Address in a Bash Script | Linux Journal
# sh valid_ip.sh
[Link] : good
a.b.c.d : bad
[Link] : good
[Link] : good
[Link] : good
[Link] : bad
[Link] : good
192.168.0 : bad
1234.123.123.123 : bad
In the function valid_ip, the if statement uses a regular expression to make sure the subject IP address
consists of four dot separated numbers:
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
If that test passes then the code inside the if statement separates the subject IP address into four parts at
the dots and places the parts in an array:
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
It does this by momentarily changing bash's Internal Field Separator variable so that rather than parsing
words as whitespace separated items, bash parses them as dot separated. Putting the value of the subject
IP address inside parenthesis and assigning it to itself thereby turns it into an array where each dot
separated number is assigned to an array slot. Now the individual pieces are tested to make sure they're
all less than or equal to 255 and the status of the test is saved so that it can be returned to the caller:
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
Note that there's no need to test that the numbers are greater than or equal to zero because the regular
expression test has already eliminated any thing that doesn't consist of only dots and digits.
Load 3 comments ([Link]
Corporate Patron
[Link] 3/6
24/10/2018 Validating an IP Address in a Bash Script | Linux Journal
([Link]
([Link]
Recent Articles
Simulate Typing with This C Program (/content/simulate-typing-c-program)
Jim Hall (/users/jim-hall)
(/content/simulate-typing-c-program)
(/content/pioneers-open-source-eren-niazi-part-i-start-movement-and-open-source-revolution-redefining)
Pioneers in Open Source--Eren Niazi, Part I: the Start of a Movement and the Open-Source Revolution Redefining the
Data Center (/content/pioneers-open-source-eren-niazi-part-i-start-movement-and-open-source-revolution-redefining)
Petros Koutoupis (/users/petros-koutoupis)
Review: System76 Oryx Pro Laptop (/content/review-system76-oryx-pro)
Robert J. Hansen (/users/robert-j-hansen)
(/content/review-system76-oryx-pro)
Weekend Reading: Tor and Tails (/content/weekend-reading-tor-and-tails)
Carlie Fairchild (/users/carlie-fairchild)
(/content/weekend-reading-tor-and-tails)
When the Problem Is the Story (/content/when-problem-story)
Doc Searls (/users/doc-searls)
(/content/when-problem-story)
Doing Date Math on the Command Line - Part II (/content/doing-date-math-
command-line-part-ii)
Mitch Frazier (/users/mitch-frazier)
[Link] 4/6
24/10/2018 Validating an IP Address in a Bash Script | Linux Journal
(/content/doing-date-math-command-line-part-ii)
Limited Time Offer
Take Linux Journal for a test drive. Download our September issue for FREE.
Email
I give consent to receive e-mail from Linux Journal.
Submit
Linux Journal Week in Review
Sign up to get all the good stuff delivered to your inbox every week.
Enter your email. Get the newsletter.
I give my consent to be emailed
SUBSCRIBE
(/subscribe)
Connect With Us
([Link] ([Link]
([Link]
Powered by currently celebrating its 24th year of publication, is the original magazine of the global Open Source community.
Linux Journal,
© 2018 Linux Journal, LLC. All rights reserved.
PRIVACY POLICY (/CONTENT/PRIVACY-STATEMENT) TERMS OF SERVICE (/TERMS-SERVICE) ADVERTISE (/SPONSORS)
SUBSCRIBE (/SUBSCRIBE) MASTHEAD (/CONTENT/MASTHEAD) RSS FEEDS (/RSS_FEEDS)
RENEW (/RENEW) NEWSLETTERS (/ENEWSLETTERS)
[Link] 5/6
24/10/2018 Validating an IP Address in a Bash Script | Linux Journal
BACKISSUES (/DIGITAL) FAQ (/CONTENT/LINUX-JOURNAL-20- MERCHANDISE
FAQ) (HTTP://[Link]/)
CUSTOMER SERVICE
(/SUBS/CUSTOMER_SERVICE) AUTHORS (/AUTHOR) CONTACT US (/ABOUTUS)
([Link]
LETTERS TO EDITOR (/CONTACT)
[Link] 6/6