As I have gone over this a few times, thought it would be good to document it somewhere.
With the evolution and ubiquity of cloud services (and focusing specifically here on cloud infrastructure) and with many providers offering some sort of internal private IP space mapped somehow to real public IPs (EC2, VPC, VLANs...), it would be good to have some easy way to find which public IP is linked to our server.
There are a few ways to achieve this. Let's take a look at a couple.
To demonstrate it, let's launch a new server on Amazon EC2 and map and Elastic IP to it. The Elastic IP is 126.96.36.199.
If we check which is the server IP from the command line this is what we see:
So, we are not seeing the Elastic IP (Public) of the server but a RFC 1918 internal IP address (10.98.0.43) that is only routable within the EC2 Cloud.
Now, in many situations you may want to know the real public IP with which you can i.e. SSH into the server or maybe need it to script something or to authorize it with an external service (i.e. at Cloudways we use this to populate an mcollective custom fact with the public IP of each server we manage). So, how can we get it from the server itself?.
Very easy, first and my preferred way is using the following command:
dig +short @resolver1.opendns.com myip.opendns.com
This will basically use an OpenDNS utility to find out our public IP. Here we can see the results on our server:
So here we have our Elasitc IP. Any method to find out our public IP will depend on an external service. I like this one cause we are using OpenDNS that we can expect to be around for a while.
And here we have our second method:
There are several variants of this just using different internet services:
curl ipecho.net/plain; echo
That all produce the same result:
So, the Elastic (public) IP of our server.
Now this of course works with any hosting provider besides AWS. Just choose the method that works best for you.