Add script to fetch public IP from multiple providers

This script attempts to retrieve the public IP address by querying multiple services in a randomized order. If successful, it writes the IP to /currentip; otherwise, it outputs an error message.
This commit is contained in:
Alexandre
2025-11-24 08:11:13 +01:00
committed by GitHub
parent 7342b37a06
commit 5a41d1c265

View File

@@ -0,0 +1,33 @@
#!/bin/bash
get_public_ip() {
local urls=(
"https://ifconfig.co/ip"
"https://api64.ipify.org"
"https://ipecho.net/plain"
)
local i j tmp url ip
# FisherYates shuffle to randomize the order
for ((i=${#urls[@]}-1; i>0; i--)); do
j=$((RANDOM % (i + 1)))
tmp=${urls[i]}
urls[i]=${urls[j]}
urls[j]=$tmp
done
# Try each provider in random order until one works
for url in "${urls[@]}"; do
if ip=$(curl -fsS --max-time 10 "$url"); then
printf '%s\n' "$ip"
return 0
fi
done
return 1
}
# Write to /currentip, fail if none of the services respond
if ! get_public_ip > /currentip; then
echo "Failed to get public IP from all providers" >&2
fi