Skip to content

Instantly share code, notes, and snippets.

@remimikalsen
Last active May 24, 2024 15:52
Show Gist options
  • Save remimikalsen/ea08b4a5e4280f9c18d7def4041a6264 to your computer and use it in GitHub Desktop.
Save remimikalsen/ea08b4a5e4280f9c18d7def4041a6264 to your computer and use it in GitHub Desktop.
Track your public IP and cache the updated IP locally
#/bin/bash
# https://theawesomegarage.com/blog/godaddy-terminated-my-free-dns-management-api-now-what
# This script is used to check the current IP-address, and update a cache file if needed
# The cache file is used by other scripts to check if their IP needs to be updated
# The reason for using a current IP-cache, is to reduce load on calling ipinfo.io
# which has a rate limit of 50.000 calls a month. With 5 domains, checking every 5
# minutes, that is almost 50.000 calls. With a common check, we reduce the number to
# Define the cache file
CACHE_FILE="/tmp/.myPublicIP"
# Make the API call and get the response and HTTP status code
response=$(curl -s -w "%{http_code}" http://ipinfo.io/json)
http_code=$(echo "$response" | tail -c 4)
new_ip=$(echo $response | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b")
# Check if the HTTP status code is 200 (OK)
if [ "$http_code" -eq 200 ]; then
# Check if the cache file exists
if [ -f "$CACHE_FILE" ]; then
# Read the old IP from the cache file
old_ip=$(cat "$CACHE_FILE")
else
old_ip=""
fi
# Compare the old IP with the new IP
if [ "$new_ip" != "$old_ip" ]; then
# Update the cache file with the new IP
echo "$new_ip" > "$CACHE_FILE"
[ -e $CACHE_FILE ] && currentIP=`cat $CACHE_FILE`
echo "New IP: $currentIP"
fi
else
echo "Error getting IP. HTTP Status Code: $http_code"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment