How to find your public IP address with the Linux command line

Sometimes I need to find out what the public IP address of a particular machine is. If I have access to a web browser on that machine I just hope over to a service such as or to find this information. However, on a remote Linux server it is not practical to use the web browser method. So, instead, I use the following hack.

I enter the following line into a Linux command line:

# curl -s | grep '"Box"' | egrep -o '[0-9.]+'

Pretty useful stuff this. If you need to use this command often it might be a good idea to create a script with the command so that you need not have to remember it. Create a new file using your favorite text editor. Enter the following lines:

curl -s | grep '"Box"' | egrep -o ‘[0-9.]+'

Now save the file as something like /usr/bin/myipaddress. Grant it executable privileges like this:

# chmod +x /usr/bin/myipaddress

Now you have a script that you can access from anywhere on your computer by running myipaddress in the command line. It will output your current public IP address. This can be quite useful if you use things like IP-based authentication, or if you use a dynamic DNS service.

Although the above example should work most of the time, there might be times when the service that gives you your public IP address is down or has changed the format with which they display the data, thus breaking the script. Here’s a backup method in case the command shown earlier does not work for you. It used the service

# links -dump | awk "/IP is/{print $NF}"

You could also use this with lynx:

# lynx -dump | awk "/IP is/{print $NF}"

Again, feel free to enter this command into a script like I showed you earlier. It will make using the command a breeze.

13 thoughts on “How to find your public IP address with the Linux command line”

  1. Pingback: Find your external IP from the CLI « Linux & Stuff

  2. When I copy-pasted the script into my own file, I saw that your quote marks don’t match up.

    … ‘[0-9.]+’

    I changed the first quote before the [ character to ‘, making the final product read:

    curl -s | grep ‘”Box”‘ | egrep -o ‘[0-9.]+’

    By the way, I apologize for the slight messiness of this, but it’s very difficult to quote a quote mark. ;)

  3. … evidently, the author doesn’t read our replies, otherwise, I’d have had a successful execution of the script file, because I would have copied corrected text. …

  4. Using ifconfig works just as well, you’ll still need to grep for the proper lines, and then possibly use sed to extract the actual IP address as this script does, and it doesn’t rely on a specific site actually being up…

  5. Sorry for the delayed reply. You can also use the following command to get your public IP:

    wget -q -O -|sed -e 's/.*Current IP Address: //' -e 's/<.*$//'

Leave a Comment

Your email address will not be published. Required fields are marked *