Chinaunix首页 | 论坛 | 博客
  • 博客访问: 100002
  • 博文数量: 64
  • 博客积分: 2570
  • 博客等级: 少校
  • 技术积分: 605
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 11:00
文章分类

全部博文(64)

文章存档

2011年(1)

2010年(25)

2009年(38)

我的朋友

分类: LINUX

2009-11-27 15:00:45

A script to parse IP address and check it validity
[Chinese]一个解析IP地址并检查其合法性的脚本(使用awk)

For example, ip address is that 192.168.0.1
This script would do 2 checks,
one is to check each section is a 3 integer.
the others is to check they could not larger than 255.


#!/bin/sh
CheckIPAddress()
{
        echo $1 > /tmp/tmpserverip
        echo $1 |grep "^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$" > /dev/null
        if [ $? = 1 ];  then
                return 1
        else
        a=$(cut -d. -f1 /tmp/tmpserverip)
        b=$(cut -d. -f2 /tmp/tmpserverip)
        c=$(cut -d. -f3 /tmp/tmpserverip)
        d=$(cut -d. -f4 /tmp/tmpserverip)

        for loop in $a $b $c $d
        do
                if [ $loop -ge 255 ] || [ $loop -le 0 ]; then
                        return 2
                fi
                done
        fi

        return 0
}

This one is the one which using 'awk'.


CheckIPAddress1()
{
        echo $1 | awk -F. '{if($1~/[0-9]/) print $0}'
        a=`echo $1 | awk -F. '{print $1}'`
        b=`echo $1 | awk -F. '{print $2}'`
        c=`echo $1 | awk -F. '{print $3}'`
        d=`echo $1 | awk -F. '{print $4}'`
        echo $a $b $c $d

        for loop in $a $b $c $d
        do
                if [ $loop -ge 255 ] || [ $loop -le 0 ]; then
                        return 2
                fi
        done

}

if      CheckIPAddress1 $1; then
        echo "error"
else
        echo "success"
fi


阅读(500) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~