在內網環境下,曾有需求通過 JavaScript 直接獲取用戶的機器名與 IP 地址。早期方案利用 IE 專有的 `ActiveXObject` 調用系統組件(`WScript.Network`、`rcbdyctl.Setting`),但此方案**極度依賴 IE、需降低安全設置、僅限內網可信環境**,且在現代瀏覽器(Edge/Chrome/Firefox/Safari)中**完全不可用**。本文解析原理、展示代碼、深度剖析局限,並給出現代合規的替代方案。
<script type="text/javascript">
function getClientPcName() {
try {
var wsh = new ActiveXObject("WScript.Network");
return wsh.ComputerName;
} catch (e) {
console.error('獲取電腦名失敗:', e);
return 'Unknown';
}
}
function getClientIp() {
try {
// 需安裝特定 ActiveX 控件 (rcbdyctl.Setting),非系統內置
var ctrl = new ActiveXObject("rcbdyctl.Setting");
return ctrl.GetIPAddress;
} catch (e) {
console.error('獲取 IP 失敗:', e);
return 'Unknown';
}
}
// 測試
alert(getClientPcName() + ' - ' + getClientIp());
</script>
| 環境 | IE 版本 | 安全區域 | ActiveX 設置 | 結果 |
|---|---|---|---|---|
| VS 本地調試 (Cassini/IIS Express) | 系統 IE | 本地內網 / 受信任站點 | 默認較寬鬆 / 用戶手動調低 | ✅ 成功 |
| 發布到 IIS (內網) | 系統 IE | 內網區域 | 默認「提示」或「禁用」未標記為安全的 ActiveX | ❌ 彈窗提示/靜默失敗 |
| 現代瀏覽器 (Edge/Chrome/FF) | N/A | N/A | **完全不支持 ActiveX** | ❌ 直接報錯 `ActiveXObject is not defined` |
| 移動端/非 Windows | N/A | N/A | 無 ActiveX 架構 | ❌ 不可用 |
// 後端 (Node.js/Express 示例)
app.get('/api/client-info', (req, res) => {
// 獲取真實 IP (考慮反向代理)
const ip = req.headers['x-forwarded-for']?.split(',')[0]?.trim()
|| req.headers['x-real-ip']
|| req.connection.remoteAddress
|| req.socket.remoteAddress;
res.json({
ip: ip.replace('::ffff:', ''), // IPv6 映射 IPv4 格式處理
userAgent: req.headers['user-agent'],
timestamp: Date.now()
});
});
// 前端調用
fetch('/api/client-info').then(r => r.json()).then(data => {
console.log('客戶端 IP:', data.ip);
// 機器名無法獲取,不可嘗試
});
**優點**:全瀏覽器支持、無客戶端依賴、安全可控、支持 IPv6、CDN/代理鏈下正確獲取真實 IP。
async function getLocalIPs() {
const ips = new Set();
try {
const pc = new RTCPeerConnection({ iceServers: [] });
pc.createDataChannel('');
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
pc.onicecandidate = (e) => {
if (e.candidate) {
const match = e.candidate.candidate.match(/(\d+\.\d+\.\d+\.\d+)/);
if (match) ips.add(match[1]);
}
};
await new Promise(r => setTimeout(r, 1000)); // 等待候選收集
pc.close();
} catch (e) {
console.warn('WebRTC IP 檢測失敗:', e);
}
return Array.from(ips);
}
// 使用
getLocalIPs().then(ips => console.log('本地網卡 IP:', ips)); // 如 ['192.168.1.100', '10.0.0.5']
**注意**:僅獲取**本地網卡 IP**(內網 IP),非公網出口 IP。部分瀏覽器/mDNS 隱藏策略可能返回 `xxxx.local`。隱私合規需用戶知情同意。
IIS 開啟 Windows 認證,前端無感知,後端直接獲取 `User.Identity.Name` (DOMAIN\username) 及機器名(需額外查詢 AD)。**不暴露 IP/機器名給前端 JS**,安全性最高。
// 使用 FingerprintJS (開源庫)
import FingerprintJS from '@fingerprintjs/fingerprintjs';
const fp = await FingerprintJS.load();
const result = await fp.get();
console.log('訪問者 ID:', result.visitorId); // 基於瀏覽器/硬件特徵生成的穩定 ID
// 組件: UserAgent, Canvas, WebGL, AudioContext, 字體列表, 屏幕分辨率等
**用途**:設備識別、防欺詐、個性化、**非**機器名/IP,但無需權限、跨瀏覽器、合規。
| 需求 | 推薦方案 | 關鍵點 |
|---|---|---|
| 獲取用戶公網/出口 IP | 後端 API + X-Forwarded-For | 標準、準確、無前端依賴 |
| 獲取用戶內網 IP (WebRTC) | WebRTC ICE Candidate | 僅內網 IP、隱私敏感、需告知用戶 |
| 獲取機器名/硬件信息 | 客戶端程序 / 擴展 / Electron | 需用戶安裝、高權限、內網受控環境 |
| 設備唯一標識 (非機器名) | FingerprintJS / Cookie / LocalStorage | 無權限、跨瀏覽器、合規 |
| 內網單點登錄/身份識別 | Windows 集成認證 (Kerberos) | 無感知、安全、後端拿身份 |
| 維護極舊 IE6 內網系統 | ActiveX (含簽名/分發/策略) | 高成本、高風險、計劃淘汰 |
**JavaScript 在瀏覽器沙箱中無權直接訪問機器名或網卡 IP**,這是瀏覽器安全模型的基石。ActiveX 方案是 IE 時代的歷史產物,伴隨著極高的安全風險、部署成本與兼容性負債。**現代 Web 開發中,堅決放棄前端直獲 IP/機器名**,轉而採用:
若遇到「必須在前端獲取機器名」的需求,請與產品/安全/架構溝通,**重新評估業務必要性與技術可行性**,尋找合規替代路徑。