出於安全考慮,現代瀏覽器嚴格限制 JS 訪問客戶端硬件信息(MAC、IP)。本文分析歷史方案(ActiveX)的原理、侷限,並給出現代合規替代方案。
<!-- 僅 IE 生效,需用戶降低安全級別或添加信任站點 -->
<object id="locator" classid="CLSID:76A64158-CB41-11D1-8B02-00600806D9B6"></object>
<object id="foo" classid="CLSID:75718C9A-F029-11d1-A1AC-00C04FB6C223"></object>
<script for="foo" event="OnObjectReady(objObject, objAsyncContext)" language="JScript">
if (objObject.IPEnabled) {
MACAddr = objObject.MACAddress;
IPAddr = objObject.IPAddress(0);
sDNSName = objObject.DNSHostName;
}
</script>
<script language="JScript">
var service = locator.ConnectServer();
service.Security_.ImpersonationLevel = 3;
service.InstancesOfAsync(foo, 'Win32_NetworkAdapterConfiguration');
</script>
// Node.js Express 示例
app.get('/api/client-ip', (req, res) => {
const ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress;
res.json({ ip });
});
前端調用:fetch('/api/client-ip').then(r => r.json()).then(console.log)
// 僅能獲取局域網 IP,不穩定,部分瀏覽器已限制
const pc = new RTCPeerConnection({iceServers: []});
pc.createDataChannel('');
pc.createOffer().then(o => pc.setLocalDescription(o));
pc.onicecandidate = e => {
if (e.candidate) {
const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
const match = ipRegex.exec(e.candidate.candidate);
if (match) console.log('本地 IP:', match[1]);
}
};
結論:純前端無法獲取 MAC。業務需求通常可通過以下替代:
ActiveX 方案已成為歷史。現代 Web 開發應接受「前端不可獲取 MAC/IP」的事實,轉向服務端獲取 IP、設備指紋識別、後端風控等合規技術棧。安全與隱私是不可逆的趨勢。