There are a lot of ways to find out your public IP address on a Linux or Unix-like systems.
In this guide, you’ll be introduced to some of the fastest ways to get your public IP address via your terminal.
Getting Public IP Address Using DNS
The below command uses
dig to make a DNS query to OpenDNS (which is an American company that provides DNS resolution services):
$ dig myip.opendns.com @resolver1.opendns.com +short
This will output your public IP address in a text form.
If the above command is slow and you want another DNS server, you can also use Google or Akamai DNS services:
$ dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | tr -d '"'
Notice we made a TXT DNS record query, and since it returns the public IP address in double quotes, we used tr command to simply remove it, try it out!
$ dig whoami.akamai.net @ns1-1.akamaitech.net +short
Getting Public IP Address By Making an HTTP Request
You can always make an HTTP request to third-party services that detects your public IP address and returns it in a simple plain text, here are some of working commands:
wget command on ipinfo.io:
$ wget -qO- ipinfo.io/ip
curl on ipinfo.io:
$ curl ipinfo.io/ip
Or you may want to change the service, ipecho.net for instance:
$ wget -qO- ipecho.net/plain
$ curl ipecho.net/plain
There are a lot of servers out there, make sure you pick the one with the lowest latency (you ping the servers and see the lowest latency in ms).
Here are some HTTP endpoints that sends your public IP address in plain text form:
You can make the requests to these third-party servers using either
wget commands as shown previously!
Alright, now you have a lot of ways to get your public IP address in your Linux machine, I suggest you use
time command on all DNS and HTTP servers and see which is the fastest in your case.
Learn also: How to Enable/Disable IP Forwarding in Linux.