46 lines
1.3 KiB
PHP
46 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
class NetworkService
|
|
{
|
|
public static function getNetworkInterfaces()
|
|
{
|
|
// 使用 `ifconfig` 来获取接口和 IP 地址
|
|
$output = shell_exec('ifconfig');
|
|
return self::parseNetworkInfo($output);
|
|
}
|
|
|
|
private static function parseNetworkInfo($output)
|
|
{
|
|
$interfaces = [];
|
|
$interface = null;
|
|
$lines = explode("\n", $output);
|
|
|
|
foreach ($lines as $line) {
|
|
// 匹配接口名称
|
|
if (preg_match('/^([a-zA-Z0-9-]+): flags=/', $line, $matches)) {
|
|
$interface = $matches[1];
|
|
$interfaces[$interface] = [
|
|
'ip' => null,
|
|
'mask' => null,
|
|
];
|
|
}
|
|
// 匹配 IPv4 地址
|
|
if ($interface && preg_match('/inet ([\d\.]+)/', $line, $matches)) {
|
|
$interfaces[$interface]['ip'] = $matches[1];
|
|
}
|
|
// 匹配子网掩码
|
|
if ($interface && preg_match('/netmask ([\d\.]+)/', $line, $matches)) {
|
|
$interfaces[$interface]['mask'] = $matches[1];
|
|
}
|
|
}
|
|
|
|
// 输出调试信息,检查解析到的接口
|
|
error_log(print_r($interfaces, true));
|
|
|
|
return $interfaces;
|
|
}
|
|
|
|
}
|