Get WAN IP address via shell

Sometimes one needs to get the WAN IP address via shell.

#!/bin/sh

set -e
set -u

C_DIG="$(which dig)"

DEBUG=0

while [[ ${#} -gt 0 ]]; do
    KEY="${1}"

    case "${KEY}" in
        -d|--debug)
            DEBUG=1
            shift
        ;;
    esac
done

QUERY_TYPE="A"
DIG_OPTIONS="+short"

DNS_SERVER="resolver1.opendns.com"
QUERY_VALUE="myip.opendns.com"

# short version: dig @resolver1.opendns.com A myip.opendns.com +short
IP_ADDRESS="$(${C_DIG} @${DNS_SERVER} ${QUERY_TYPE} ${QUERY_VALUE} ${DIG_OPTIONS})"
RC=${?}

# if the IP address could be successfully retrieved by querying OpenDNS echo it and exit
if [ ${RC} -eq 0 ]; then
    if [ ${DEBUG} -eq 1 ]; then
        echo "Server queried: OpenDNS"
    fi

    echo "${IP_ADDRESS}"

    exit 0
fi

DNS_SERVER="ns1-1.akamaitech.net"
QUERY_VALUE="whoami.akamai.net"

# short version: dig @ns1-1.akamaitech.net A whoami.akamai.net +short
IP_ADDRESS="$(${C_DIG} @${DNS_SERVER} ${QUERY_TYPE} ${QUERY_VALUE} ${DIG_OPTIONS})"
RC=${?}

# if the IP address could be successfully retrieved by querying Akamai echo it and exit
if [ ${RC} -eq 0 ]; then
    if [[ "${DEBUG}" == "-d" ]]; then
        echo "Server queried: Akamai"
    fi

    echo "${IP_ADDRESS}"

    exit 0
fi

DNS_SERVER="ns1.google.com"
QUERY_VALUE="o-o.myaddr.l.google.com"
QUERY_TYPE="TXT"

# short version: dig @ns1.google.com TXT o-o.myaddr.l.google.com +short
IP_ADDRESS="$(${C_DIG} @${DNS_SERVER} ${QUERY_TYPE} ${QUERY_VALUE} ${DIG_OPTIONS})"
RC=${?}

# if the IP address could be successfully retrieved by querying Google echo it and exit
if [ ${RC} -eq 0 ]; then
    if [[ "${DEBUG}" == "-d" ]]; then
        echo "Server queried: Google"
    fi

    echo "${IP_ADDRESS}"

    exit 0
fi

exit 1

Source

This has been taken from https://unix.stackexchange.com/a/81699 and put into a small script to provide some kind of failover if one service might not be available.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.