Check IP

Check ob eine IP-Adresse valide ist ( BASH )

#!/bin/bash
## IF NOTHING IS GIVEN USE DEFAULT TO SHOW FUNCTIONALITY
IP=${1:-192.168.1.1}

## TESTING IF WE GOT 4 OCTETS
if [[ ${IP} =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        ## SPLITTING INTO 4 PARTS SEPARATED BY SPACE AND REMOVE LEADING "0" EG 098 -> 98
        OCTETS=$( echo ${IP} | tr -s '.' ' ' | sed 's/^0*//g; s/\.0*/\./g' )
        for OCTET in ${OCTETS}
        do
                ## IF ONE OCTET IS GRATER THAN 255 IT'S NOT VALID
                if [ ${OCTET} -gt 255 ]; then
                        (( ERROR ++ ))
                fi
        done
else
        echo "${IP} :: NOT VALID"
        exit 1
fi 

if [ "${ERROR}" ]; then
        echo "${IP} :: NOT VALID"
        exit 1
fi

unset ERROR

Wird die obige Abfrage in eine Funktion überführt, lässt sich innerhalb von Scripte die Validität von IP-Adressen sehr leicht überprüfen.

#!/bin/bash

function check_ip () {
    ## IF NOTHING IS GIVEN USE DEFAULT TO SHOW FUNCTIONALITY
    IP=${1}

    ## TESTING IF WE GOT 4 OCTETS
    if [[ ${IP} =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
            ## SPLITTING INTO 4 PARTS SEPARATED BY SPACE AND REMOVE LEADING "0" EG 098 -> 98
            OCTETS=$( echo ${IP} | tr -s '.' ' ' | sed 's/^0*//g; s/\.0*/\./g' )
            for OCTET in ${OCTETS}
            do  
                    ## IF ONE OCTET IS LOWER THAN 255 IT'S NOT VALID
                    if [ ${OCTET} -gt 255 ]; then
                            (( ERROR ++ ))
                    fi  
            done
    else
            echo "${IP} :: NOT VALID"
            exit 1
    fi  

    if [ "${ERROR}" ]; then
            echo "${IP} :: NOT VALID"
            exit 1
    fi  

    unset ERROR

}

## CALL FUNCTION
check_ip ${1:-10.1.1.4}