萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 取得伺服器 MAC 地址跨平台類(Windows ipconfig / Linux ifconfig 解析)

透過呼叫系統指令 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},同時相容 : 與 - 分隔符。
  • Linux 新增 ip link show 後備指令,ifconfig 於新版發行版可能未預裝。
  • 移除舊式建構子 function MacAddInfo(),改用 __construct。
  • 屬性加上型別宣告、回傳 ?string 明確表達可能為 null。

進階:取得所有網卡 MAC(含虛擬介面)

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);
}

權限與部署提醒

  • PHP 需具備 exec 執行權限(disable_functions 未禁用)。
  • Linux 容器若無 ip/ifconfig,安裝 iproute2 / net-tools 套件。
  • 虛擬介面(docker0、veth、lo)亦會被掃描到,若需只取實體網卡,需結合 ethtool -i 判斷驅動類型或排除 lo/virbr 等前綴。
copyright © 萬盛學電腦網 all rights reserved