Operations 8 min read

How to Reliably Retrieve Your Public IP with Shell Scripts and Multiple Fallbacks

Learn how to accurately determine your ISP‑assigned public IP address using simple shell commands, online services, and a robust Bash script that falls back between dig and curl with random host selection, ensuring reliable results for home‑based services and DDNS updates.

Open Source Linux
Open Source Linux
Open Source Linux
How to Reliably Retrieve Your Public IP with Shell Scripts and Multiple Fallbacks

Determining the public IP address assigned by an ISP is a common issue for home broadband users, especially when using dynamic IPs that change on each connection.

Dynamic IPs affect services running on home bandwidth, requiring frequent updates of server IPs for monitoring, network storage, etc.; DDNS services help, but built‑in router clients may be paid or unstable, so using DNS provider APIs (e.g., Aliyun, Cloudflare) is an alternative.

The key parameter for DDNS updates is the current public IP, which can be obtained via various online services.

1. Obtain Public IP with Shell Commands

Browser method

Opening URLs such as https://checkip.amazonaws.com in a browser returns the public IP; many similar services exist:

https://checkip.amazonaws.com
https://api.ipify.org
https://ifconfig.me/ip
https://icanhazip.com
https://ipinfo.io/ip
https://ipecho.net/plain
https://checkipv4.dedyn.io

cURL method

From the command line, curl can fetch the IP, e.g.:

curl checkip.amazonaws.com

dig method

The dig command can query OpenDNS to return the client’s IP:

dig +short myip.opendns.com @resolver1.opendns.com

Install dig on Debian‑based systems with apt-get install dnsutils. This method transfers less data than HTTP, but DNS queries may be filtered by ISPs.

2. Use a Shell Script to Retrieve the Public IP

The following Bash script first tries the dig method; if it fails, it falls back to curl using a list of hosts, selecting one at random and retrying until a valid IPv4 address is obtained.

#!/bin/bash
# This script tries to ensure it gets the current IP address (as assigned by the ISP) from
# OpenDNS and other online services as fallbacks

hosts=("checkip.amazonaws.com" "api.ipify.org" "ifconfig.me/ip" "icanhazip.com" "ipinfo.io/ip" "ipecho.net/plain" "checkipv4.dedyn.io")

CURL=`which curl`
DIG=`which dig`

check=$($DIG +short myip.opendns.com @resolver1.opendns.com A)

if [ ! $? -eq 0 ] || [ -z "$check" ] || [[ ! $check =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    echo "Unable to get your public IP address by OpenDNS service, try to another way."
    count=${#hosts[@]}

    while [ -z "$check" ] && [[ $count -ne 0 ]]; do
        selectedhost=${hosts[ $RANDOM % ${#hosts[@]} ]}
        check=$($CURL -4s https://$selectedhost | grep '[^[:blank:]]') && {
            if [ -n "$check" ] && [[ $check =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
                break
            else
                check=""
                count=$(expr $count - 1)
                echo "The host $selectedhost returned an invalid IP address."
            fi
        } || {
            check=""
            count=$(expr $count - 1)
            echo "The host $selectedhost did not respond."
        }
    done
fi

if [ -z "$check" ]; then
    echo "Unable to get your public IP address. Please check your internet connection."
    exit 1
fi

echo "Your public IP address is $check"

exit 0

The script uses dig as the primary method; if it fails, it switches to curl with a random host from the list, using the -4s options to enforce IPv4 and suppress progress output.

3. Summary

Relying on a single online service to obtain the public IP is fragile; using multiple fallback methods and random selection for curl improves reliability and avoids overloading any single service, which could lead to bans.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

cURLPublic IPnetwork operationsshell scriptdigDDNS
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.