How do I get the local IP address of the server using PHP?

后端 未结 7 1092
不思量自难忘°
不思量自难忘° 2020-12-31 14:21

I am developing a PHP application that will be run only on the local network of a business. The application will be installed to the server using a custom installer like thi

7条回答
  •  醉酒成梦
    2020-12-31 15:18

    I am also pretty sure this isn't possible. Or if it is possible, the results won't be reliable.

    A server may have multiple IP addresses. Also, the IP address used for HTTP on the server may not be the one used to reach the server from elsewhere (if there's a reverse proxy or NAT involved). The SERVER_ADDR variable shows the IP address that was used to call a PHP script; this information is passed from the web server, so it won't help for a PHP script that's running stand-alone (i.e. from a shell).

    Let's look at this another way. What problem are you trying to solve? That is, why do you need the local IP of the server? Rather than getting help implementing a solution that won't work, let's look at the original issue and see if there's another solution that IS possible.

    I should point out that depending on your operating system, there may be ways to get a list of IPs assigned to various interfaces by parsing the output of a shell command like ifconfig -a or ip addr. But I don't know your OS, so I can't suggest how that would work for you.

    $h = popen("ip addr | awk '/inet/{print$2}'");
    $ip_list = array();
    while ($ip_list[] = fread($h, 15)) { }
    pclose($h);
    

    You could put more logic into the PHP to avoid using awk in a pipe, but you get the idea.

提交回复
热议问题