简体   繁体   中英

Simply find the ip address of server

The following code to find the actual local ip address (eg 192.168.1.X ) of the host server has run fine on a dev machine

$ip = getHostByName( getHostName() );

Transferring it to another server it started to output 127.0.0.1

It seems that getHostName() returns localhost which in turn gets converted to 127.0.0.1 by getHostByName().

Looking at other questions here it seemed that $_SERVER['SERVER_ADDR'] might solve the puzzle but this is also returning 127.0.0.1

Checking and searching the output from phpinfo() returns no clues to the actual ip address of the machine.

Seriously, does anyone know a bullet proof (simpler the better) way of getting the ip address of the machine running the script? Why is it so hard to get such fundamental data without doing back flips?

I really don't want to be hardcoding the ip address in a config file...

恐怕一般来说是不可能的-用于连接服务器的真实IP可能会在到达服务器之前被转换...

If You need all list of interfaces try system(); to execute shell's command and get result to web-server. For example:

system('ifconfig', $LIP);
system('ipconfig', $WIP);
echo "Linux:".$LIP."<br>Win:".$WIP."<br>;

Try this:

$ip = getHostByName( $_SERVER['HTTP_HOST'] );

It should resolve the IP of the host user is accessing site by.

For example, if you have your website accessed via http://localhost/ it will give you 127.0.0.1. But for http://www.mydomain.tld/ it should return the IP for www.mydomain.tld.

Please note that /etc/hosts can affect the names resolution if the domain is listed there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM