Good Linux question — answering as the UphillTech team:
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.). The DNS response protocol is standardised (the format will stay compatible). Historically, DNS services (Akamai, Google Public DNS, OpenDNS, ..) tend to survive much longer and are more stable, more scalable, and generally more...
Full answer by Timo Tijhof: https://unix.stackexchange.com/a/81699 (CC BY-SA 4.0).
Need Linux help for your business? UphillTech.