How to (always) get your server’s IP address

If you're new here, you may want to subscribe to my RSS feed.
Thanks for reading my blog!

Here is how to (always) get your server's a IP address. Works on Unix/Linux.

<?php
if (empty($_SERVER['SERVER_ADDR'])) {
$server_host = `hostname -f`;
$server_ip = `host $server_host`;

if (preg_match('#(\d+\.\d+\.\d+\.\d+)#', $server_ip, $matches)) {
$server_ip = $matches[1];
} else {
$server_ip = '127.0.0.1';
}
} else {
$server_ip = $_SERVER['SERVER_ADDR'];
}

echo $server_ip;
?>

Tags: , , , ,

Leave a Reply