原文嘗試在伺服器端呼叫 `nbtstat -A
// 原始碼片段
ProcessStartInfo psi = new ProcessStartInfo("nbtstat", "-A " + IP);
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
var proc = Process.Start(psi);
string output = proc.StandardOutput.ReadToEnd();
// 以 Regex 解析 "Mac Address = XX-XX-XX-XX-XX-XX"
此碼僅能在**伺服器與客戶端同一網段、開啟 NetBIOS、無防火牆阻擋**的理想環境運作,實務上幾乎不成立。
| 需求 | 推薦方案 | 說明 |
|---|---|---|
| 識別唯一瀏覽器/裝置 | Cookie + 指紋辨識 | HttpOnly Cookie + Client JS 產生指紋(Canvas、User-Agent、螢幕解析度等) |
| 追蹤使用者會話 | ASP.NET Session / JWT | 標準驗證機制,支援分散式架構 |
| 防止重複投票/濫用 | IP + Cookie + 行為分析 | 單一 IP 非唯一使用者,需綜合判斷 |
| 內網資產管理 | 代理軟體/掃描工具 | 由管理端主動掃描,非 Web 被動取得 |
| 裝置綁定/雙因子驗證 | WebAuthn / FIDO2 | 標準化硬體金鑰/生物辨識,安全且尊重隱私 |
// 僅供參考:加入超時、錯誤處理、輸入驗證
public static string TryGetMacFromNbtstat(string ip)
{
if (!IPAddress.TryParse(ip, out _)) return "Invalid IP";
try
{
var psi = new ProcessStartInfo("nbtstat", $"-A {ip}")
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
using (var proc = Process.Start(psi))
{
if (!proc.WaitForExit(3000)) { proc.Kill(); return "Timeout"; }
string output = proc.StandardOutput.ReadToEnd();
var match = Regex.Match(output, @"MAC Address\s*=\s*([0-9A-F-]{17})", RegexOptions.IgnoreCase);
return match.Success ? match.Groups[1].Value : "Not Found";
}
}
catch (Exception ex) { return $"Error: {ex.Message}"; }
}
總結:Web 應用**無法**也**不應該**直接取得客戶端 MAC。請根據實際業務需求,選擇 Cookie、Session、裝置指紋、WebAuthn 等現代標準技術實作識別與驗證功能。