您现在的位置是:网站首页> 编程资料编程资料
Shell脚本实现IP地址合法性判断_linux shell_
2023-05-26
519人已围观
简介 Shell脚本实现IP地址合法性判断_linux shell_
做unix/linux下的开发,脚本编写的功力是少不了的,作为shell编程,也是博大精深的一个技术领域,这里为了学习,就写一个简单的判断IP地址是否合法的微型脚本程序,这个小程序也是非常有用的。
IP地址是32位的,可以由4个十进制数值表示,每个数值的范围都是0~255.
#!/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='
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
如果你存储成valid_ip.sh直接运行就可以得到如下结果
# 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
相关内容
- Shell脚本8种字符串截取方法总结_linux shell_
- Shell字符串比较相等、不相等方法小结_linux shell_
- Shell中删除某些文件外所有文件的3个方法_linux shell_
- Shell脚本IF条件判断和判断条件总结_linux shell_
- Shell脚本中判断输入变量或者参数是否为空的方法_linux shell_
- Shell脚本中判断输入参数个数的方法_linux shell_
- Shell最多支持多少个参数?_linux shell_
- Python执行Linux系统命令的4种方法_linux shell_
- bash: /usr/bin/autocrorder: /usr/bin/python^M: bad interpreter: No such file or directory_linux shell_
- 写出健壮Bash Shell脚本的一些技巧总结_linux shell_
