在 PHP 中获取本机 MAC 地址,核心思路是执行系统命令(如 ipconfig 或 ifconfig)并解析输出。由于跨平台差异,Windows 和 Linux/macOS 的命令及返回格式不同,需根据运行环境分别处理。

Windows 环境下的实现
在 Windows 服务器上,使用 ipconfig /all 命令可获取网卡信息。PHP 通过 exec() 或 shell_exec() 调用该命令,并从输出中提取包含 "Physical Address" 的行。

Windows 的 ipconfig /all 输出较为固定,每块网卡的物理地址紧跟在 "Physical Address" 之后。代码逻辑为:执行命令 -> 按行分割 -> 正则匹配目标行 -> 提取十六进制值。需注意服务器可能禁用了 exec 函数,此时需检查 php.ini 中的 disable_functions 配置。
Linux/Unix 环境下的实现
在 Linux 或 macOS 系统中,推荐使用 ip link show 或 ifconfig -a。以现代 Linux 为例,ip link show 的输出更简洁,MAC 地址通常标记为 "link/ether"。

<?php
function getServerMacAddress() {
$os = PHP_OS;
$mac = null;
if (stripos($os, 'WIN') !== false) {
// Windows: ipconfig /all
exec('ipconfig /all', $output, $return_var);
if ($return_var === 0 && !empty($output)) {
foreach ($output as $line) {
if (preg_match('/Physical Address\.\.\s*:\s*([0-9A-Fa-f]{2}-[0-9A-Fa-f]{2}-[0-9A-Fa-f]{2}-[0-9A-Fa-f]{2}-[0-9A-Fa-f]{2}-[0-9A-Fa-f]{2})/', $line, $matches)) {
$mac = $matches[1];
break;
}
}
}
} else {
// Linux/Unix: ip link show or ifconfig
if (function_exists('exec')) {
// Try modern 'ip' command first
exec('ip link show', $output, $return_var);
if ($return_var === 0 && !empty($output)) {
foreach ($output as $line) {
// Skip loopback
if (strpos($line, 'lo:') !== false || strpos($line, 'state DOWN') !== false) continue;
if (preg_match('/link\/ether\s+([0-9a-f]{12})/', $line, $matches)) {
$mac = strtoupper(substr($matches[1], 0, 2) . ':' . substr($matches[1], 2, 2) . ':' . substr($matches[1], 4, 2) . ':' . substr($matches[1], 6, 2) . ':' . substr($matches[1], 8, 2) . ':' . substr($matches[1], 10, 2));
break;
}
}
}
// Fallback to ifconfig if 'ip' didn't work or isn't available
if (!$mac) {
exec('ifconfig -a', $output, $return_var);
if ($return_var === 0 && !empty($output)) {
foreach ($output as $line) {
if (strpos($line, 'lo:') !== false) continue;
if (preg_match('/ether\s+([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})/', $line, $matches)) {
$mac = strtoupper($matches[1]);
break;
}
}
}
}
}
}
return $mac ? $mac : 'Unable to retrieve MAC address';
}
echo getServerMacAddress();
程序在 Windows 上输出类似 "XX-XX-XX-XX-XX-XX" 的格式,在 Linux 上输出 "XX:XX:XX:XX:XX:XX"。若服务器禁用了 exec 系列函数,将返回错误提示。多网卡环境下,代码返回第一个符合条件的活跃网卡 MAC。
Linux 环境下可能存在多个网卡(如 eth0, lo 等),通常忽略回环接口(lo)。代码需遍历所有网卡,筛选出非回环且状态为 UP 的接口,提取其 MAC 地址。若服务器使用较老的 ifconfig,则需匹配 "HWaddr" 字段。同样依赖系统命令执行权限。
完整兼容代码与注意事项
以下代码封装了跨平台逻辑,自动检测操作系统并调用相应命令,返回第一个有效的非回环 MAC 地址。
该脚本优先尝试 Windows 路径,失败后回退至 Linux 路径。在实际部署时,请确保 Web 用户(如 www-data 或 IUSR)有权限执行相关系统命令。若所有方法均失败,可能因安全策略限制导致。