我正在编写一个需要列出服务器所有外部IP的脚本。它需要使用多个NIC。在PHP中获取所述IP地址的最佳方法是什么?
如果有任何帮助,我发现了这个问题,但它是针对Python而不是PHP; Python, How to get all external ip addresses with multiple NICs
答案 0 :(得分:3)
获取除Link-local以外的所有接口的(IPv4)IP:
<?php
$command = '/sbin/ifconfig | awk -v RS="\n\n" \'{ for (i=1; i<=NF; i++) if ($i == "inet" && $(i+1) ~ /^addr:/) address = substr($(i+1), 6); if (address != "127.0.0.1") printf "%s\t%s\n", $1, address }\' | awk \'{ print $2}\'';
$ips = shell_exec($command);
echo $ips;
?>
在Debian Linux上测试。
答案 1 :(得分:2)
如果您使用的是基于Linux的服务器,则应该为您执行此操作:
$command = "/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
$ips = exec($command);
echo $ips;
答案 2 :(得分:0)
我认为这可能是最适合您的
$command = "/sbin/ifconfig | grep inet | grep -v ':\|127.0.0.1' | awk '{print $2}'";
exec($command, $ips);
return $ips;
希望这会有所帮助