'IP'에 해당되는 글 1건

  1. 2018.04.01 validate ip address in bash
2018. 4. 1. 21:13

validate ip address in bash


Linux의 bash shell script을 작성하는데, ip addresss를 입력받는 부분을 작성 중이다.

입력 받은 주소의 적합성을 검사하려고 하는데, 생각보다 간단하지 않았다.


최종 완성된 코드를 올리니, 참고하시라... (귀찮아서 설명을 하지 않음을 이해해 주세요)

#!/bin/bash


function is_number()

{

local src=$1

local stat=1

tdst=`expr $src + 1` 2> /dev/null

stat=$?

return $stat

}


function validate_ip()

{

    local  lip=$1

    local  stat=255

local renumexp='^[0-9]+$'

    if [[ $lip != ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then

        OIFS=$IFS

        IFS='.'

        sip=($lip)

        IFS=$OIFS


printf "0: %s\n" ${sip[0]}

printf "1: %s\n" ${sip[1]}

printf "2: %s\n" ${sip[2]}

printf "3: %s\n" ${sip[3]}


stat=0


vip=${sip[0]}

if [ $stat -eq 0 ] ; then

is_number $vip 2> /dev/null

if [ $? -eq 0 ] ; then

if [[ $vip -gt 255 ]] ; then

stat=1

fi

else

# not number

stat=11

fi

fi


vip=${sip[1]}

if [ $stat -eq 0 ] ; then

is_number $vip 2> /dev/null

if [ $? -eq 0 ] ; then

if [[ $vip -gt 255 ]] ; then

stat=2

fi

else

# not number

stat=12

fi

fi


vip=${sip[2]}

if [ $stat -eq 0 ] ; then

is_number $vip 2> /dev/null

if [ $? -eq 0 ] ; then

if [[ $vip -gt 255 ]] ; then

stat=3

fi

else

# not number

stat=13

fi

fi


vip=${sip[3]}

if [ $stat -eq 0 ] ; then

is_number $vip 2> /dev/null

if [ $? -eq 0 ] ; then

if [[ $vip -gt 255 ]] ; then

stat=4

fi

else

# not number

stat=14

fi

fi

    fi

    return $stat

}



read ip


if validate_ip $ip; then

  echo "success ($ip)"

  exit 0

else

  echo "fail ($ip)"

  exit 1

fi



참고 사이트는

1. validate ip

https://unix.stackexchange.com/questions/111841/regular-expression-in-bash-to-validate-ip-address

https://stackoverflow.com/questions/13777387/check-for-ip-validity


2. check number

https://stackoverflow.com/questions/806906/how-do-i-test-if-a-variable-is-a-number-in-bash

https://www.unix.com/shell-programming-and-scripting/21668-how-check-whether-string-number-not.html


이다.