萬盛學電腦網

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

PHP 獲取伺服器 MAC 地址跨平台實作:Windows/Linux 通用類別

應用場景

軟體授權綁定、設備指紋識別、資產管理系統需獲取伺服器網卡物理位址 (MAC Address)。PHP 無內建函數,需呼叫系統指令解析輸出。

跨平台實作類別

<?php
/**
 * 獲取機器網卡 MAC 地址
 * 支援 Windows / Linux / Unix 類系統
 */
class MacAddInfo {
    private $return_array = array();
    private $mac_addr;

    public function __construct($os_type = null) {
        $os_type = $os_type ?: PHP_OS;
        switch (strtolower($os_type)) {
            case 'linux':
            case 'unix':
            case 'solaris':
            case 'aix':
                $this->forLinux();
                break;
            default: // Windows
                $this->forWindows();
                break;
        }
        $this->parseMacAddress();
    }

    private function forWindows() {
        @exec('ipconfig /all', $this->return_array);
        if (!$this->return_array) {
            $ipconfig = $_SERVER['WINDIR'] . '/system32/ipconfig.exe';
            if (is_file($ipconfig)) {
                @exec($ipconfig . ' /all', $this->return_array);
            } else {
                @exec($_SERVER['WINDIR'] . '/system/ipconfig.exe /all', $this->return_array);
            }
        }
    }

    private function forLinux() {
        @exec('ifconfig -a', $this->return_array);
        // 現代 Linux 建議使用 `ip link` 或 `cat /sys/class/net/*/address`
        // ifconfig 已在部分精簡版移除
    }

    private function parseMacAddress() {
        $pattern = '/[0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}/i';
        foreach ($this->return_array as $line) {
            if (preg_match($pattern, $line, $matches)) {
                $this->mac_addr = $matches[0];
                break;
            }
        }
    }

    public function getMac() {
        return $this->mac_addr;
    }
}

// 使用範例
$mac = new MacAddInfo();
echo 'Server MAC: ' . $mac->getMac();

關鍵點解析

  1. 系統指令差異:Windows 用 ipconfig /all,Linux 用 ifconfig -a (或 ip link)。
  2. 正則匹配:支援 : (Linux) 與 - (Windows) 兩種分隔符,大小寫不敏感。
  3. 多網卡處理:程式碼回傳第一張匹配到的實體網卡 MAC。若需全部,可回傳陣列。
  4. 權限需求:exec() 需 PHP 設定 disable_functions 未禁用,且 Web 使用者需有執行指令權限。

現代 Linux 更佳替代方案

<?php
function getLinuxMacs() {
    $macs = array();
    // 方法 1: 讀取 sysfs (最快、無需執行指令)
    $net_dir = '/sys/class/net/';
    if (is_dir($net_dir)) {
        foreach (scandir($net_dir) as $iface) {
            if ($iface === '.' || $iface === '..' || $iface === 'lo') continue;
            $addr_file = $net_dir . $iface . '/address';
            if (is_readable($addr_file)) {
                $mac = trim(file_get_contents($addr_file));
                if ($mac !== '00:00:00:00:00:00') {
                    $macs[$iface] = $mac;
                }
            }
        }
    }
    return $macs;
}

// 方法 2: `ip -j link` JSON 輸出 (iproute2 新版支援)
function getLinuxMacsJson() {
    exec('ip -j link', $out);
    $json = json_decode(implode('', $out), true);
    $macs = array();
    foreach ($json as $dev) {
        if (isset($dev['address']) && $dev['address'] !== '00:00:00:00:00:00') {
            $macs[$dev['ifname']] = $dev['address'];
        }
    }
    return $macs;
}

/sys/class/net/*/address 為核心虛擬檔案系統介面,無需 fork 進程,效能極佳且無權限疑慮(唯讀)。

安全性提醒

  • MAC 可被偽造(ip link set dev eth0 address XX:XX:XX:XX:XX:XX),不可作為唯一安全憑證。
  • 容器環境 (Docker/K8s) 所見 MAC 為虛擬網卡,非實體硬體地址。
  • 生產環境建議結合 CPU ID、主機板序號、磁碟 UUID 多因子綁定。
copyright © 萬盛學電腦網 all rights reserved