軟體授權綁定、設備指紋識別、資產管理系統需獲取伺服器網卡物理位址 (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();
ipconfig /all,Linux 用 ifconfig -a (或 ip link)。: (Linux) 與 - (Windows) 兩種分隔符,大小寫不敏感。exec() 需 PHP 設定 disable_functions 未禁用,且 Web 使用者需有執行指令權限。<?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 進程,效能極佳且無權限疑慮(唯讀)。
ip link set dev eth0 address XX:XX:XX:XX:XX:XX),不可作為唯一安全憑證。