Methods to detect public IP address in bash

48,084

Solution 1

curl ipinfo.io/ip

Or

wget -q -O - ipinfo.io/ip

Or

lynx -source ipinfo.io/ip

get public ip address

Solution 2

curl ifconfig.me would be the best choice, in case you don't have curl:

wget -qO- ifconfig.me/ip

Solution 3

How much public public IP are you looking for? What if the machine is behind NAT?

  • curl / wget / netcat (nc) <URL> which contains requester's address: should work most of the time, but may the site may be unreachable from the machine (be it firewall or temporary/permanent unavailability). You'll get the most public IP you can.

  • ifconfig: must run as root, otherwise you'd have to try /sbin/ifconfig or /usr/sbin/ifconfig as well. What if the machine has more NICs? How do you tell what IP is the right one? What if only IPv6 is used on the machine's LAN? In any case, you'll get the least public IP you can (and possibly a wrong one if more interfaces are configured on the machine - which often is the case these days with omnipresent virtualization using network tap devices and/or).

  • /etc/hostname: does not need to exist, on many systems it is /etc/HOSTNAME, and it does not contain IP address rather it should contain the hostname (usually the FQDN).

The point is, that the ways in which it can fail are numerous and you probably should consider either a) specifying more precisely what systems you are targeting or b) whether you really need to know the IP at all - is a solution that seems to work in simple cases worth using when it fails miserably in slightly more complicated setup? If you think you need the IP, prepare a way to handle failures gracefully in cases where you either don't get the IP at all or you get a wrong one.

Solution 4

If on an AWS EC2 you can use:

curl checkip.amazonaws.com

NOTE: this service can be used from any web client.

Solution 5

Try this command:

wget -O - -q icanhazip.com
Share:
48,084
Jeroen Ooms
Author by

Jeroen Ooms

#rstats developer and staff RSE for @ropensci at UC Berkeley.

Updated on July 17, 2022

Comments

  • Jeroen Ooms
    Jeroen Ooms almost 2 years

    As part of an installation script, I want to make an "educated guess" about the machines public IP address. It should be as robust as possible, working on a variety of hosts and platforms. Here is an example:

    https://gist.github.com/4669037

    This script uses 3 methods and then defaults to the value of /etc/hostname. I have only tested this on Ubuntu so far. Will this be likely to work on other distributions? And are there additional methods that I could add?