首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 取得網卡 MAC 地址的跨平台類別實作

     編輯:PHP 相關知識

在 PHP 中讀取伺服器硬體資訊(如 MAC 地址)常用於授權驗證、設備識別等場景。本文提供一個支援 Windows 與 Linux 的封裝類別,自動偵測作業系統並呼叫對應指令解析結果。

核心邏輯

  • Windows:呼叫 ipconfig /all,解析「實體位址」。
  • Linux/Unix:呼叫 ifconfig -a 或 ip link,解析 ether 或 HWaddr 欄位。
  • 使用正則表達式提取標準 MAC 格式(XX:XX:XX:XX:XX:XX 或 XX-XX-XX-XX-XX-XX)。

完整程式碼

<?php
/**
 * 取得機器網卡 MAC 地址
 * 支援 Windows / Linux 系統
 */
class MacAddInfo {
    private $return_array = [];
    public $mac_addr = '';

    public function __construct($os_type = '') {
        // 自動偵測作業系統
        $os_type = $os_type ?: PHP_OS;
        switch (strtolower($os_type)) {
            case 'linux':
            case 'unix':
            case 'solaris':
            case 'aix':
                $this->forLinux();
                break;
            default:
                $this->forWindows();
                break;
        }
        $this->parseMacAddress();
    }

    /** Windows 環境呼叫 ipconfig */
    private function forWindows() {
        @exec("ipconfig /all", $this->return_array);
        if (empty($this->return_array)) {
            // 嘗試指定完整路徑
            $windir = $_SERVER['WINDIR'] ?? 'C:\\Windows';
            $paths = [
                "$windir/system32/ipconfig.exe",
                "$windir/system/ipconfig.exe"
            ];
            foreach ($paths as $path) {
                if (is_file($path)) {
                    @exec("$path /all", $this->return_array);
                    break;
                }
            }
        }
    }

    /** Linux 環境呼叫 ifconfig */
    private function forLinux() {
        @exec("ifconfig -a", $this->return_array);
        // 部分精簡系統無 ifconfig,可嘗試 ip link
        if (empty($this->return_array)) {
            @exec("ip link show", $this->return_array);
        }
    }

    /** 從指令輸出中解析 MAC 地址 */
    private function parseMacAddress() {
        $pattern = '/([0-9a-f]{2}[:-]){5}[0-9a-f]{2}/i';
        foreach ($this->return_array as $line) {
            if (preg_match($pattern, $line, $matches)) {
                $this->mac_addr = $matches[0];
                break;
            }
        }
    }
}

// 使用範例
$mac = new MacAddInfo();
echo "偵測到的 MAC 地址:" . ($mac->mac_addr ?: '未偵測到');
?>

使用說明與注意事項

  1. 權限需求:PHP 執行身分需具備執行 ipconfig/ifconfig 權限(通常 CLI 模式無問題,Web 模式可能受限於 disable_functions 或使用者權限)。
  2. 多網卡環境:本類別回傳第一個偵測到的實體網卡 MAC,虛擬網卡(如 Docker、VPN)可能優先被讀取。如需特定網卡,請擴充解析邏輯過濾介面名稱(如 eth0、ens33)。
  3. PHP 版本:相容 PHP 5.3+,建議 PHP 7.4+ 以獲得最佳效能。
  4. 安全性:避免在公開頁面直接輸出 MAC,防止資訊洩露。

替代方案

若環境安裝 php-sysvsem、php-posix 擴展,亦可嘗試透過 /sys/class/net/*/address(Linux)讀取檔案方式獲取,避免執行外部指令,安全性更高。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved