If you google something like “find my public IP,” you will probably find dozens of websites that as soon as you open them display your public IP such as this one:
It may also give you the geographical location of your IP, but even if they don’t, it’s as easy to google that also. And they usually come with a ton of annoying ads.
The Fast Way
How do you do the same on the command line or when you want to write a script that retrieves your public IP?
Similarly, there are services that can give you that information. The fastest way appears to be by using a DNS lookup with dig.
Here is how it works:
netbeez$ dig @resolver1.opendns.com myip.opendns.com +short
This command uses the DNS server resolver1.opendns.com to look up the URL myip.opendns.com resolver1.opendns.com. The OpenDNS server resolver1.opendns.com is programmed to return the IP of the requestor when the URL that is being looked up is resolver1.opendns.com. And it spits out your public IP – just that.
I tested this on my Linux box, and it returns results in less that 10 milliseconds. If that’s all you need, this is probably the best way to do it.
Google, and others, also maintain similar services:
netbeez$ dig TXT +short o-o.myaddr.l.google.com @ns1.google.com"99.35.16.xxx"
As you can see the google equivalent service returned the IP enclosed in double quotes. You need to be aware of that if you are parsing this output.
The dig method returns the IP and just that.The same way websites give you the geolocation of our IP, you can get that information with a few different services, and one of them is ipinfo.io as follows:
netbeez$ curl ipinfo.io
"city": "San Jose",
"org": "AS7018 AT&T Services, Inc.",
As you can see this simple curl request to ipinfo.io returns the IP, the hostname, the geolocation, the timezone, and the service provider. If you want just the IP you can use this command:
netbeez$ curl ipinfo.io/ip
This command takes 20-40 more milliseconds than the dig command, but when that’s not important the additional information you get can be pretty handy.
ipinfig/io is free for non-commercial usage, but if you are looking for a paid API they offer several plans that will fit your needs.