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!

Tagged , , , ,

2 thoughts on “Ubuntu Tech Snippet #13 – Get your public IP in terminal

  1. Nathan Osman says:

    A slightly shorter variant of this is:

    $ curl icanhazip.com

  2. Faster variant:
    $ time dig +short myip.opendns.com @resolver1.opendns.com

    real 0m0.061s
    user 0m0.020s
    sys 0m0.004s

    (Of course you can use alias in your .bashrc to make it shorter)

    And yours:

    $ time echo $(curl -s https://api.ipify.org)

    real 0m0.718s
    user 0m0.012s
    sys 0m0.012s

    Look at http://unix.stackexchange.com/questions/22615/how-can-i-get-my-external-ip-address-in-bash

Tell us what you thought!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: