Get the external IP address in shell without dig in 2016?
An alternative is Google DNS:
myip(){ dig @8.8.8.8 -t txt o-o.myaddr.l.google.com |
grep "client-subnet" |
grep -o "\([0-9]\{1,3\}\.\)\{3\}\([0-9]\{1,3\}\)" ; }
If your system does not have dig, then host will be exactly equivalent:
myip(){ host -t txt o-o.myaddr.l.google.com 8.8.8.8 |
grep -oP "client-subnet \K(\d{1,3}\.){3}\d{1,3}"; }
Both GNU grep (Perl-like -P
) and basic (BRE) regex are shown.
And, of course the original site, will also work.
With dig:
myip(){ dig myip.opendns.com @208.67.220.222 |
grep "^myip\.opendns\.com\." |
grep -o "\([0-9]\{1,3\}\.\)\{3\}\([0-9]\{1,3\}\)" ; }
And with host:
myip(){ host myip.opendns.com 208.67.220.222 |
grep -oP "^myip\.opendns\.com.* \K(\d{1,3}\.){3}(\d{1,3})" ; }
The two snippets above will work with any of this four OpenDNS resolver addresses:
echo 208.67.22{0,2}.22{0,2}
If the direct DNS solution fails in the future, use curl to one of this sites (urls):
IFS=$'\n' read -d '' -a urls <<-'_end_of_text_'
api.ipify.org
bot.whatismyipaddress.com/
canhazip.com/
checkip.dyndns.com/
corz.org/ip
curlmyip.com/
eth0.me/
icanhazip.com/
ident.me/
ifcfg.me/
ifconfig.me/
ip.appspot.com/
ipecho.net/plain
ipof.in/txt
ip.tyk.nu/
l2.io/ip
tnx.nl/ip
wgetip.com/
whatismyip.akamai.com/
_end_of_text_
Call an array address like this:
$ i=5; curl -m10 -L "http://${urls[i]}"
116.132.27.203
In some sites https may also work.