【问题标题】:Is it possible to find which network interface client is connected to with PHP?是否可以使用 PHP 找到连接到哪个网络接口客户端?
【发布时间】:2014-06-27 10:42:31
【问题描述】:
我想查找连接的网络接口客户端。有可能吗?
如果可以使用 Bash 或其他脚本语言。我可以接受。
我正在开发 Freebsd。
下面是代码的样子。
function get_connected_interface(){
//...
}
echo get_connected_interface(); //should print network interface. for example em0
【问题讨论】:
标签:
php
bash
shell
network-programming
freebsd
【解决方案1】:
如果您使用的是 Apache,PHP 会将 $_SERVER["SERVER_ADDR"] 设置为客户端连接到服务器的 destination ip 地址。
如果您使用的是 nginx、lighttpd 或其他网络服务器,请查看只有 <?php phpinfo(); ?> 的页面的结果,以了解如何获取 目标的ip地址 >(您的服务器的 IP 地址之一)
无论如何,您都可以使用这个 PHP 脚本来启动 ifconfig 并搜索具有该 IP 地址的接口。
我会这么说:
function get_connected_interface() {
static $interfaces=array();
if (!count($interfaces)) {
$curif="";
// launch ifconfig and parse its result (inet/inet6)
// but only at first function call
exec("ifconfig",$out);
foreach($out as $line) {
if (preg_match("#^([a-z0-9\.]*): #",$line,$mat)) {
$curif=$mat[1];
}
if (preg_match("#inet ([0-9\.]*) #",$line,$mat)) {
$interfaces[$mat[1]]=$curif;
}
if (preg_match("#inet6 ([0-9a-fA-F:]*) #",$line,$mat)) {
$interfaces[$mat[1]]=$curif;
}
}
}
return $interfaces[$_SERVER["SERVER_ADDR"]];
}