Shell script realizes IP address legality judgment _linux shell

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.