透過呼叫系統指令 ipconfig /all(Windows)或 ifconfig -a(Linux/Unix),以正則擷取 MAC 位址。封裝為 MacAddInfo 類別,自動偵測 PHP_OS 選擇解析策略,支援多網卡環境取第一張實體網卡 MAC。
<?php
class MacAddInfo
{
private array $output = [];
private ?string $macAddr = null;
public function __construct(string $osType = '')
{
$os = $osType ?: PHP_OS;
switch (strtolower($os)) {
case 'linux':
case 'freebsd':
case 'darwin': // macOS
case 'sunos': // Solaris
$this->parseLinux();
break;
default: // Windows、AIX 等
$this->parseWindows();
}
$this->extractMac();
}
private function parseWindows(): void
{
@exec('ipconfig /all', $this->output);
if (!$this->output) {
$ipconfig = ($_ENV['WINDIR'] ?? 'C:\\Windows') . '\\system32\\ipconfig.exe';
@exec("$ipconfig /all", $this->output);
}
}
private function parseLinux(): void
{
@exec('ifconfig -a', $this->output);
// 現代 Linux 也可用 `ip link show`,輸出更穩定
if (!$this->output) @exec('ip link show', $this->output);
}
private function extractMac(): void
{
$pattern = '/([0-9a-f]{2}[:-]){5}[0-9a-f]{2}/i';
foreach ($this->output as $line) {
if (preg_match($pattern, $line, $m)) {
$this->macAddr = strtoupper($m[0]);
break;
}
}
}
public function getMac(): ?string
{
return $this->macAddr;
}
}
// 使用範例
$mac = new MacAddInfo();
echo $mac->getMac() ?? '未偵測到 MAC'; // 例:00:1A:2B:3C:4D:5E
PHP_OS 常數自動判斷作業系統,免傳參。([0-9a-f]{2}[:-]){5}[0-9a-f]{2},同時相容 : 與 - 分隔符。ip link show 後備指令,ifconfig 於新版發行版可能未預裝。function MacAddInfo(),改用 __construct。?string 明確表達可能為 null。function getAllMacs(): array
{
$macs = [];
$pattern = '/([0-9a-f]{2}[:-]){5}[0-9a-f]{2}/i';
@exec(PHP_OS_FAMILY === 'Windows' ? 'ipconfig /all' : 'ip link show', $out);
foreach ($out as $line) {
if (preg_match_all($pattern, $line, $m)) {
foreach ($m[0] as $mac) $macs[] = strtoupper($mac);
}
}
return array_unique($macs);
}
exec 執行權限(disable_functions 未禁用)。ip/ifconfig,安裝 iproute2 / net-tools 套件。ethtool -i 判斷驅動類型或排除 lo/virbr 等前綴。