None of the most polled answers will reliably return the serverโs public address. Usually $_SERVER['SERVER_ADDR'] will be correct, but if you access the server via VPN, it will most likely return an internal network address rather than a public address, and even if it is not on the same network, some configurations will be empty or there will be a different meaning.
Similarly, there are scripts in which $host= gethostname(); $ip = gethostbyname($host); $host= gethostname(); $ip = gethostbyname($host); will not return the correct values โโbecause it relies on both DNS (internal or external records) and server hostname parameters to extrapolate the server IP address. Both of these steps are potentially malfunctioning. For example, if the hostname of the server is formatted as a domain name (i.e. HOSTNAME=yahoo.com ), then (at least in my php5.4 / Centos6 setup) gethostbyname scan right before searching for Yahoo.com address, and not local server.
Also, since gethostbyname reverts to the public DNS records of the test server with unpublished or incorrect public DNS records (for example, you access the server using localhost or IP address, or if you redefine public DNS using your local hosts ) , then you will return either without an IP address (it will simply return the host name), or, even worse, it will return the wrong address specified in the public DNS records if it exists or there is a wildcard for the domain.
Depending on the situation, you can also try the third approach by doing something like this:
$external_ip = exec('curl http://ipecho.net/plain; echo');
This has its drawbacks (it depends on the specific third-party site, and there may be network settings that route outgoing connections through another host or proxy), and how gethostbyname it can be slow. I honestly don't know which approach will be the most correct, but the lesson to be taken to heart is that the specific scenarios / configurations will lead to the wrong conclusions for all of these approaches ... so if possible, make sure that the approach , use returns the expected values.
Ben D Apr 19 '15 at 17:06 2015-04-19 17:06
source share