How do I find my server's IP address in PHP(CLI)

前端 未结 6 1043
梦谈多话
梦谈多话 2020-12-13 09:12

Aside from the obvious (localhost, 127.0.0.1) does PHP (command line interface!) have a mechanism for discovering the IP of the computer the script is running on?

6条回答
  •  误落风尘
    2020-12-13 09:40

    I know this is a fairly old question, but there doesn't seem to be a definitive answer (in as much as one is possible.) I've had a need to determine this value, both on *NIX boxes and on Win X boxes. Also from a CLI executed script as well as a non-CLI script. The following function is the best I've come up with, which borrows on different concepts people have spoke of over the years. Maybe it can be of some use:

    function getServerAddress() {
        if(isset($_SERVER["SERVER_ADDR"]))
        return $_SERVER["SERVER_ADDR"];
        else {
        // Running CLI
        if(stristr(PHP_OS, 'WIN')) {
            //  Rather hacky way to handle windows servers
            exec('ipconfig /all', $catch);
            foreach($catch as $line) {
            if(eregi('IP Address', $line)) {
                // Have seen exec return "multi-line" content, so another hack.
                if(count($lineCount = split(':', $line)) == 1) {
                list($t, $ip) = split(':', $line);
                $ip = trim($ip);
                } else {
                $parts = explode('IP Address', $line);
                $parts = explode('Subnet Mask', $parts[1]);
                $parts = explode(': ', $parts[0]);
                $ip = trim($parts[1]);
                }
                if(ip2long($ip > 0)) {
                echo 'IP is '.$ip."\n";
                return $ip;
                } else
                ; // TODO: Handle this failure condition.
            }
            }
        } else {
            $ifconfig = shell_exec('/sbin/ifconfig eth0');
            preg_match('/addr:([\d\.]+)/', $ifconfig, $match);
            return $match[1];
        }
        }
    }
    

提交回复
热议问题