Valid IP Address

Post Reply
User avatar
jessica
Site Admin
Posts: 31
Joined: Thu Sep 06, 2018 3:17 pm
Location: Cincinnati, Ohio
Contact:

Valid IP Address

Post by jessica » Mon Nov 26, 2018 2:00 pm

A BASH script to test for valid IP Addresses




#!/bin/bash

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 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}

IP=`dig +short myip.opendns.com @resolver1.opendns.com`
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
LOGFILE="$DIR/update-ip.log"
IPFILE="$DIR/update-ip.ip"

if ! valid_ip $IP; then
echo "Invalid IP address: $IP" >> "$LOGFILE"
exit 1
fi

if [ ! -f "$IPFILE" ]
then
touch "$IPFILE"
fi

if grep -Fxq "$IP" "$IPFILE"; then
# code if found
echo "IP is still $IP. Exiting" >> "$LOGFILE"
exit 0
else
echo "IP has changed to $IP" >> "$LOGFILE"
TMPFILE=$(mktemp /tmp/temporary-file.XXXXXXXX)
cat > ${TMPFILE} << EOF
{
"Comment":"$COMMENT",
"Changes":[
{
"Action":"UPSERT",
"ResourceRecordSet":{
"ResourceRecords":[
{
"Value":"$IP"
}
],
"Name":"$RECORDSET",
"Type":"$TYPE",
"TTL":$TTL
}
}
]
}
EOF

# Do the actual send to google script and tell them the new IP address
echo file://"$TMPFILE" >> "$LOGFILE"
echo "" >> "$LOGFILE"
rm $TMPFILE
fi

# All Done - cache the IP address for next time
echo "$IP" > "$IPFILE"
Post Reply