- Newest
- Most votes
- Most comments
Try
<?php
$ip_address = file_get_contents('http://169.254.169.254/latest/meta-data/public-ipv4');
echo "Public IP address is - ".$ip_address;
echo "</br>";
?>
The public IP isn’t bound to the instance. Think of it as a NAT address. So yes the OS does not know what it’s public IP address is.
You can obtain from the metadata as per above.
Hi,
Supposing that you're using the AWS PHP SDK (see https://aws.amazon.com/sdk-for-php/)
The following should get you the full instance description for an instance with an id of 'instance-id'
$response = $ec2Client->describeInstances(array('InstanceIds' => array('instance-id')));
and the following will grab the public ip from the instance
echo $response->get('Reservations')[0]['Instances'][0]['PublicIpAddress']
Best,
Didier
Follow up: Are you suggesting the SDK because it's not possible to do this otherwise? I mean does the Ubuntu OS not actually know it's public IP, for example?
Relevant content
- asked 8 months ago
- Accepted Answerasked 4 years ago
- AWS OFFICIALUpdated 3 months ago
- AWS OFFICIALUpdated 7 months ago
- AWS OFFICIALUpdated 2 years ago
Gary, I think I see where you're going with this. gethostbyname doesn't work because it gives me that IP of checkip.amazonaws.com. But I suppose I could do a wget to the checkip machine, and since it just echos the address the result would be fairly easy to parse. But if I have to do something like that, probably using the SDK Didier mentioned would be cleaner. Still not sure why there is no access to the IP through "normal channels."
I updated my answer since then sorry. Please see updated answer with getting file from http endpoint from the meta data endpoint.
That works great. Thank Gary.
Awesome. Glad I could help.