Methods to detect public IP address in bash Methods to detect public IP address in bash shell shell

Methods to detect public IP address in bash


curl ipinfo.io/ip

Or

wget -q -O - ipinfo.io/ip

Or

lynx -source ipinfo.io/ip

get public ip address


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

wget -qO- ifconfig.me/ip


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.