a picture my son drew of a wave on a beach

External IP

rbn

I keep meaning to put these scripts somewhere I can find them and then I don’t. So here, I am putting it here - and tagging the crap out of it. Stupid brain.

This script is basically how I automate finding and updating my external/WAN IP address. Easy.

I tidied up and expanded my previously apothegmatic code using ShellCheck. I wish something like that had been around twenty years ago when I was started breaking computers. If you are a learner use it for good bash scripting habits. If not, just give up like me.

Finding the IP address in this script uses opendns Vivek has listed some alternatives

#!/bin/bash

# add this to a cronjob
# depends upon having dnsutils or dig installed.
# uses opendns.com to resolve external address [see ipcurrent]
# for alt methods see: https://www.cyberciti.biz/faq/how-to-find-my-public-ip-a>


# Check the source file exists
src=$HOME"/bin/wanip.txt"
if [ ! -f "${src}" ]
then # if not create it
  echo "null" > "${src}"
fi

# Compare the old ip address in the source file to the current WAN ip address
ipold=$(cat "${src}")
ipcurrent="$(dig +short myip.opendns.com @resolver1.opendns.com)"

if [ "${ipcurrent}" != "${ipold}" ]; then
 echo "Old IP was \"${ipold}\", new IP is ${ipcurrent}"
 echo "now replace this echo with something to actually update your ip"
 echo "tell DNS? post it somewhere?"

 echo "${ipcurrent}" > "${src}" # update the source file
else
 echo "external ip is: ${ipcurrent}"
 echo "no changes required - exiting not exciting."
fi

exit 0

Read or add a comment.
permalink