Thursday, April 12, 2012

What is the Correct php code for seeing the IP Address of the Server?





Today I have requested a dedicated IP address for our websites from our hosting. Then I wanted to check whether the IP address got changed. I tried below statement.

 echo $_SERVER['SERVER_ADDR'];

And, it was showing the new ip address. But below statement is still showing the old ip address.

echo file_get_contents("whatismyip.com")

I tried with various other sites such as whatismyipaddress.com also. But everything is showing the old ip address only

So, I would like to know whether $_SERVER['SERVER_ADDR'] is the correct way of knowing the IP address of the server, or any other suitable way available?

I asked this question in LinkedIn and this below answer look appropriate.

In your case, indeed the correct method would be:
echo $_SERVER[SERVER_ADDR];

as this would echo the IP address of the server under which the current script is executing.

On the other hand;
echo file_get_contents("whatismyip.com")

will output the source of the homepage of a website. This IP address might differ from what you get from the previous method as this is what the out side world sees. Meaning if the website is co-hosted or virtualized then the latter will give you the edge IP address of the hosted infrastructure.

And, I found below function for finding actual IP address. I decided to find the IP address of the SERVER by requesting a page which displays IP address by calling below function. (The server will be the client for this request). But this approach also showing the new ip address. I am still wondering what will the code used in whatismyip.com for finding the actual IP of the host (device) instead of showing just the virualized ip.

function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
You can subscribe to our Email posts, and you can bookmark this blog for further reading, or you can subscribe to our blog feed.

No comments:

Search This Blog