[增添]增加了网络配置服务,自动读取网络接口及对应信息

This commit is contained in:
makotocc0107
2024-09-24 16:53:57 +08:00
committed by Coding
parent 167d3c7db3
commit eb3f49f00f
4 changed files with 95 additions and 4 deletions

View File

@@ -0,0 +1,45 @@
<?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;
}
}