A Bash script that can verify the validity of the given IP address string

Source: Internet
Author: User
Tags ip number
#! /Bin/bash
Validate_ipaddress (){
Declare-I ipart1
Declare-I ipart2
Declare-I ipart3
Declare-I ipart4

Inputip = $1
# Validate it
If [-Z $ inputip]; then
Return 1
Fi

Echo $ inputip | grep-e-Q "[0-9] {1, 3 }\. [0-9] {1, 3 }\. [0-9] {1, 3 }\. [0-9] {1, 3 }"
If [$? -Ne 0]; then
Return 1
Fi

# Separate the IP address
Ippart1 =$ {inputip % .*}
Inputip =$ {inputip #*.}
Ippart2 =t2 {inputip % .*}
Inputip =$ {inputip #*.}
Ippart3 =t3 {inputip % .*}
Ippart4 =$ {inputip #*.}

# Check whether the IP number begins with zero, that is wrong syntax
# If the string begins with zero, bash cannot convert it into integer correctly
# Ipart1 and ipart4 cannot be zero
If echo $ ippart1 | grep-Q "^ 0" | echo $ ippart4 | grep-Q "^ 0"; then
Return 1
Fi

If [$ ippart2! = "0"] & Echo $ ippart2 | grep-Q "^ 0"; then
Return 1
Fi

If [$ ippart3! = "0"] & Echo $ ippart3 | grep-Q "^ 0"; then
Return 1
Fi

Ipart1 = ippart1
Ipart2 = ippart2
Ipart3 = ippart3
Ipart4 = ippart4
If [$ ipart1-GT 254] | [$ ipart2-GT 254] | [$ ipart3-GT 254] | [$ ipart4-GT 254]; then
Return 1
Fi

Return 0
}

If validate_ipaddress $1; then
Echo "legal"
Else
Echo "illegal"
Fi

Note that the {m, n} syntax is used in the RE to verify whether the IP address is valid. In this way, grep is written with-e option, because this is an extension syntax, in some UNIX and Linux grep, this syntax is also supported without-E (basic mode, non-extended mode), but it must be written as a style like \ {M, N \}.

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.