如何在PHP(CLI)中找到服务器的IP地址

Chr*_*ish 34 php ip-address

除了显而易见的(localhost,127.0.0.1)之外,PHP(命令行界面!)是否有一种机制来发现脚本运行的计算机的IP?

$_SERVER[*] 不会工作,因为这不是一个Web应用程序 - 这是一个命令行脚本.

TIA

小智 42

您可以使用获取主机名 gethostname

  • 谢谢 - 这很棒:我的解决方案是:getHostByName(getHostName()); (14认同)
  • 注意:此方法(和`gethostbynamel()`)将始终返回服务器本地主机文件中映射的任何IP.在我的测试(Ubuntu 11.10)中,这意味着如果要检查的主机名在/ etc/hosts中映射到127.0.0.1**,它将覆盖任何其他条目集. (3认同)

Ani*_*ish 32

试试这个它应该返回服务器的IP地址

$host= gethostname();
$ip = gethostbyname($host);
Run Code Online (Sandbox Code Playgroud)


Mat*_*ley 14

如果您正在使用PHP <5.3,这可能会有所帮助(至少基于*NIX的系统):

 mscharley@S04:~$ cat test.php
#!/usr/bin/env php
<?php

function getIPs($withV6 = true) {
    preg_match_all('/inet'.($withV6 ? '6?' : '').' addr: ?([^ ]+)/', `ifconfig`, $ips);
    return $ips[1];
}

$ips = getIPs();
var_dump($ips);

 mscharley@S04:~$ ./test.php
array(5) {
  [0]=>
  string(13) "72.67.113.141"
  [1]=>
  string(27) "fe80::21c:c0ff:fe4a:d09d/64"
  [2]=>
  string(13) "72.67.113.140"
  [3]=>
  string(9) "127.0.0.1"
  [4]=>
  string(7) "::1/128"
}
 mscharley@S04:~$
Run Code Online (Sandbox Code Playgroud)

或者,如果你不经常这样做,那么也许这会起作用(只是不要滥用它):

$ip = file_get_contents('http://whatismyip.org/');
Run Code Online (Sandbox Code Playgroud)


小智 8

我知道这是一个相当古老的问题,但似乎没有一个明确的答案(尽可能多的答案.)我需要在*NIX框和Win X上确定这个值框.同样来自CLI执行的脚本以及非CLI脚本.以下功能是我提出的最好的功能,它借鉴了人们多年来所提到的不同概念.也许它可以有一些用处:

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];
    }
    }
}
Run Code Online (Sandbox Code Playgroud)