【发布时间】:2010-12-21 08:08:44
【问题描述】:
除了显而易见的(localhost,127.0.0.1)外,PHP(命令行界面!)是否有一种机制可以发现运行脚本的计算机的 IP?
$_SERVER[*] 将不起作用,因为这不是 Web 应用程序 - 这是一个命令行脚本。
TIA
【问题讨论】:
标签: ip-address php
除了显而易见的(localhost,127.0.0.1)外,PHP(命令行界面!)是否有一种机制可以发现运行脚本的计算机的 IP?
$_SERVER[*] 将不起作用,因为这不是 Web 应用程序 - 这是一个命令行脚本。
TIA
【问题讨论】:
标签: ip-address php
您可以使用gethostname获取主机名
【讨论】:
gethostbynamel())将始终返回映射到服务器本地主机文件中的任何 IP。在我的测试(Ubuntu 11.10)中,这意味着如果您要检查的主机名映射到 /etc/hosts 中的 127.0.0.1 anywhere,它将覆盖任何其他条目集。
试试这个它应该返回服务器的IP地址
$host= gethostname();
$ip = gethostbyname($host);
【讨论】:
php -r "echo gethostbyname(php_uname('n'));" 显示 192.168.178.20 ...我正在使用 php 5.3.8
如果您使用的是 PHP
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:~$
或者,如果您不希望经常这样做,那么也许这会起作用(只是不要滥用它):
$ip = file_get_contents('http://whatismyip.org/');
【讨论】:
我知道这是一个相当古老的问题,但似乎没有明确的答案(尽可能多的答案。)我需要确定这个值,无论是在 *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];
}
}
}
【讨论】:
如果所有其他方法都失败了,您总是可以exec ipconfig 或 ifconfig,具体取决于您的平台,并解析结果。
【讨论】:
$ip = file_get_contents('http://icanhazip.com/');
回声 $ip;
【讨论】: