Do unix/linux under the development, scripting skill is indispensable, as Shell programming, is also a profound technical field, here in order to learn, write a simple IP address is the legal micro-script program, this small program is also very useful.
The IP address is 32-bit, and can be represented by 4 decimal digits, each of which ranges from a 0~255 value.
Copy Code code as follows:
#!/bin/bash
# Test an IP addresses 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/
& nbsp; && ${ip[2]}-le 255 && ${ip[3]}-le 255]]
& nbsp; stat=$?
fi
return $stat
}
# If run directly, execute some tests.
If [[$ (basename $ sh) "= = ' valid_ip ']]; then
ips= '
&nbs p; 4.2.2.2
a.b.c.d
192.168.1.1
0.0.0.0
255.255.255.255
255.255.255.256
192.168.0.1
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 store it as a valid_ip.sh direct run you can get the following results
Copy Code code as follows:
# sh valid_ip.sh
4.2.2.2:good
A.b.c.d:bad
192.168.1.1:good
0.0.0.0:good
255.255.255.255:good
255.255.255.256:bad
192.168.0.1:good
192.168.0:bad
1234.123.123.123:bad