脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - shell - Shell脚本实现IP地址合法性判断

Shell脚本实现IP地址合法性判断

2023-02-22 13:48shell教程网 shell

这篇文章主要介绍了Shell脚本实现IP地址合法性判断,本文给出了实现代码和运行代码,需要的朋友可以参考下

做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

延伸 · 阅读

精彩推荐