Server Behind NAT: Dynamic DNS Updates
One of my machines is serving public users but it behind NAT. Besides DHCP IP address reservation and Port Forwarding, it needed a hostname. I am using the below script to update the DDNS.
#!/bin/bash
IP_FILE="/tmp/ddns-ip.txt"
# Try to get current IP, capture both output and error
currentip="$(curl -sS --fail checkip.amazonaws.com 2> /tmp/curl_err)"
curl_status=$?
# Exit with message if we couldn't get the current IP
if [ $curl_status -ne 0 ] || [ -z "$currentip" ]; then
echo "Could not retrieve current IP: $(cat /tmp/curl_err)"
rm -f /tmp/curl_err
exit 1
fi
rm -f /tmp/curl_err
# Get old IP (empty if file missing)
oldip="$(cat "$IP_FILE" 2>/dev/null || echo "")"
# Exit silently if IP hasn't changed
if [ "$currentip" = "$oldip" ]; then
exit 0
fi
# Save new IP
echo "$currentip" > "$IP_FILE"
# Log the IP into console
echo "New IP address: $currentip"
# Trigger DDNS update
curl -sS -u username:password "https://api.dynu.com/nic/update?hostname=subdomain.example.com" | grep -v '^nochg$'
The provider, dynu.com, has a free tier which satisfies my current requirements.