Ubuntu Tech Snippet #13 – Get your public IP in terminal

Sometimes when you’re working on a project or are SSHed into a remote server, you need to find out the public IP of the device, without using a GUI web-browser.

I had to do this while working on setting up a script on my server, and came across this neat little command that will grab your public IP and print it nicely out for you to use!

All you have to do is run echo $(curl -s https://api.ipify.org) and you’re good to go!

Output from echo $(curl -c https://api.ipify.org)

Output from echo $(curl -c https://api.ipify.org)

You can also do this programatically. In python you can run this code to get the result as a JSON object:

import requests
session = requests.Session()
ret = session.get('https://api.ipify.org',
print ("Public IP Address:",ret.json()['ip'])

You’ll need to install the Python Requests module. This can be done either via pip. Just run sudo pip install requests. You can technically install it using easy_install, but please, please don’t. Just use pip.

And that’s it!

Thanks for reading! If you have any tips of your own, leave them as a comment down below and I’ll be sure to take a look at them!

%d bloggers like this: