[修改]实现读取DHCP模式并判断,优化service中读取方法

This commit is contained in:
makotocc0107
2024-10-08 17:05:11 +08:00
committed by Coding
parent d0b379eab1
commit 50ca69c958
2 changed files with 99 additions and 83 deletions

View File

@@ -6,8 +6,8 @@ class NetworkService
{
public static function getNetworkInterfaces()
{
// 使用 `ifconfig` 来获取接口和 IP 地址
$output = shell_exec('ifconfig');
// 使用 `nmcli dev show` 来获取接口信息
$output = shell_exec('nmcli dev show');
return self::parseNetworkInfo($output);
}
@@ -19,20 +19,30 @@ class NetworkService
foreach ($lines as $line) {
// 匹配接口名称
if (preg_match('/^([a-zA-Z0-9-]+): flags=/', $line, $matches)) {
$interface = $matches[1];
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('/inet ([\d\.]+)/', $line, $matches)) {
$interfaces[$interface]['ip'] = $matches[1];
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('/netmask ([\d\.]+)/', $line, $matches)) {
$interfaces[$interface]['mask'] = $matches[1];
// 匹配网关
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];
}
}
@@ -42,4 +52,19 @@ class NetworkService
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
}
}
}