I need to find my external IP address from a shell script. At the moment I use this function:
myip () {
lwp-request -o text checkip.dyndns.org | awk '{ print $NF }'
}
But it depends on perl-libwww
, perl-html-format
, perl-html-tree
installed. What other ways can I get my external IP?
Best Answer
I'd recommend getting it directly from a DNS server.
Most of the other answers below all involve going over HTTP to a remote server. Some of them required parsing of the output, or relied on the User-Agent header to make the server respond in plain text. Those change quite frequently (go down, change their name, put up ads, might change output format etc.).
Using
dig
with an OpenDNS resolver:Perhaps alias it in your
bashrc
so it's easy to rememberResponds with a plain ip address:
Syntax
(Abbreviated from https://ss64.com/bash/dig.html):
The
ANY
query type returns either an AAAA or an A record. To prefer IPv4 or IPv6 connection specifically, use the-4
or-6
options accordingly.To require the response be an IPv4 address, replace ANY with
A
; for IPv6, replace it withAAAA
. Note that it can only return the address used for the connection. For example, when connecting over IPv6, it cannot return the A address.Alternative servers
Various DNS providers offer this service, including OpenDNS, Akamai, and Google Public DNS:
Example alias that specifically requests an IPv4 address:
And for your IPv6 address:
Troubleshooting
If the command is not working for some reason, there may be a network problem. Try one of the alternatives above first.
If you suspect a different issue (with the upstream provider, the command-line tool, or something else) then run the command without the
+short
option to reveal the details of the DNS query. For example: