Finding an instance's external IP with PHP

0

I've got a lightsail ubuntu instance and I'd like to get it's public IP address with PHP. All of the following return the instance's private address:

gethostbyname(gethostname())

$_SERVER['SERVER_ADDR']

getHostByName(php_uname('n'))

Anybody know how I can get the public IP with php?

EDIT: Let me just add here - no one has actually suggested this yet, but the reason I don't really want to do a gethostbyname on the real (DNS) name of the box is that I'm actually trying to directly verify which box I'm talking to on the assumption that the DNS might be configured incorrectly.

Mike
demandé il y a 9 mois438 vues
2 réponses
2
Réponse acceptée

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.

profile picture
EXPERT
répondu il y a 9 mois
  • 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.

1

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

profile pictureAWS
EXPERT
répondu il y a 9 mois
  • 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?

Vous n'êtes pas connecté. Se connecter pour publier une réponse.

Une bonne réponse répond clairement à la question, contient des commentaires constructifs et encourage le développement professionnel de la personne qui pose la question.

Instructions pour répondre aux questions