Sometimes you really need to know your machine's public IP address, so you can use it in your scripts or applications. Not just the IP address on the local network - that's easy unless you need the IPv6 version - but the one that the rest of the internet sees. How can you find this?
You could just go to one of the many web sites you find by searching "What is my IP address", but then you need to scrape the data from the page. You could try tracing through the route your requests take to a particular site, but that's just ridiculously hard and prone to errors. There is actually a really simple way that will do the job nicely - let's take a look at that.
I've used two services that will provide you with your machine's IPv4 AND IPv6 addresses - all you need to do is store the data locally. The bash script to do this is below:
#!/bin/bash
if [[ $(($RANDOM % 2)) = 1 ]] ; then
export IP_ADDRESS_LOCAL_V4=$(curl -s -4 https://ifconfig.co)
export IP_ADDRESS_LOCAL_V6=$(curl -s -6 https://ifconfig.co)
else
export IP_ADDRESS_LOCAL_V4=$(curl -s -4 https://icanhazip.com)
export IP_ADDRESS_LOCAL_V6=$(curl -s -6 https://icanhazip.com)
fi
echo "IPv4:" $IP_ADDRESS_LOCAL_V4
echo "IPv6:" $IP_ADDRESS_LOCAL_V6
To invoke the script, you'll need to use one of the following to ensure the environment variables remain set when the script is finished:
source ./getpublicips.sh
or
. ./getpublicips.sh
Why Is There A Random Call In The Script?
I've worked with a lot of systems that make a LOT of calls to third party APIs. It's not fair to keep making calls when you're not paying for them and, more practically, if the service provider thinks you're overusing the service they might block you.
To avoid this, the script randomly chooses which of the providers to use. The result is always the same though: two environment variables containing your machine's public IPv4 and IPv6 addresses.