71 lines
2.3 KiB
PHP
71 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
class NetworkService
|
|
{
|
|
public static function getNetworkInterfaces()
|
|
{
|
|
// 使用 `nmcli dev show` 来获取接口信息
|
|
$output = shell_exec('nmcli dev show');
|
|
return self::parseNetworkInfo($output);
|
|
}
|
|
|
|
private static function parseNetworkInfo($output)
|
|
{
|
|
$interfaces = [];
|
|
$interface = null;
|
|
$lines = explode("\n", $output);
|
|
|
|
foreach ($lines as $line) {
|
|
// 匹配接口名称
|
|
if (preg_match('/^GENERAL.DEVICE: *(.+)$/', $line, $matches)) {
|
|
$interface = trim($matches[1]);
|
|
$interfaces[$interface] = [
|
|
'ip' => null,
|
|
'mask' => null,
|
|
'gateway' => null,
|
|
'dns' => [],
|
|
];
|
|
}
|
|
// 匹配 IPv4 地址
|
|
if ($interface && preg_match('/IP4.ADDRESS\[1\]: *([\d\.]+)\/(\d+)/', $line, $matches)) {
|
|
$ip = $matches[1];
|
|
$prefix = $matches[2];
|
|
// $mask = self::prefixToMask($prefix); // 获取子网掩码
|
|
$interfaces[$interface]['ip'] = $ip;
|
|
$interfaces[$interface]['mask'] = $prefix; // 设置掩码格式
|
|
}
|
|
// 匹配网关
|
|
if ($interface && preg_match('/IP4.GATEWAY: *([\d\.]+)/', $line, $matches)) {
|
|
$interfaces[$interface]['gateway'] = $matches[1];
|
|
}
|
|
// 匹配 DNS
|
|
if ($interface && preg_match('/IP4.DNS\[\d+\]: *([\d\.]+)/', $line, $matches)) {
|
|
$interfaces[$interface]['dns'][] = $matches[1];
|
|
}
|
|
}
|
|
|
|
// 输出调试信息,检查解析到的接口
|
|
error_log(print_r($interfaces, true));
|
|
|
|
return $interfaces;
|
|
}
|
|
|
|
public static function getDHCPstatus($state)
|
|
{
|
|
// 调试:检查传递的 state 参数
|
|
error_log("正在获取DHCP状态的接口: " . $state);
|
|
|
|
// 执行 nmcli 命令,获取指定连接的详细信息
|
|
$output = shell_exec('nmcli con show ' . escapeshellarg($state));
|
|
|
|
// 使用正则表达式匹配 'ipv4.method: auto'
|
|
if (preg_match('/ipv4\.method:\s+auto/', $output)) {
|
|
return true; // 如果匹配到,说明启用了 DHCP
|
|
} else {
|
|
return false; // 否则未启用 DHCP
|
|
}
|
|
}
|
|
}
|