除了显而易见的(localhost,127.0.0.1)之外,PHP(命令行界面!)是否具有一种机制来发现脚本在其上运行的计算机的IP?
[$_SERVER[*]
将不起作用,因为这不是Web应用程序-这是命令行脚本。
TIA
您可以使用gethostname
获得主机名
尝试此操作应返回服务器的IP地址
gethostname
如果您使用的是PHP <5.3,则可能会有所帮助(至少在基于* NIX的系统上:)
$host= gethostname();
$ip = gethostbyname($host);
或者,如果您不希望经常这样做,那么这也许会起作用(只是不要滥用它:]
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:~$
我知道这是一个相当老的问题,但是似乎没有一个明确的答案(尽可能多。)我需要在* NIX框和赢X个盒子。同样从CLI执行的脚本以及非CLI脚本。以下功能是我想出的最好的功能,它借鉴了人们多年来讨论过的不同概念。也许有一定用处:
$ip = file_get_contents('http://whatismyip.org/');
如果其他所有方法均失败,则始终可以根据平台使用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];
}
}
}
ipconfig或ifconfig并解析结果。
$ ip = file_get_contents('exec');
echo $ ip;