using System.Text.RegularExpressions;
using System.Diagnostics;
public class MacHelper
{
public static string GetClientMac(string ip)
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = "nbtstat",
Arguments = "-A " + ip,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (Process proc = Process.Start(psi))
{
string output = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
// 清理輸出空格
output = output.Replace(" ", "").Replace("\t", "").Replace("\r", "").Replace("\n", "");
// 正則提取 MAC
Regex reg = new Regex("MacAddress=(?[0-9A-F-]{17})", RegexOptions.IgnoreCase);
Match m = reg.Match(output);
if (m.Success) return m.Groups["mac"].Value;
// 錯誤處理
if (output.Contains("Hostnotfound")) return "Host not found";
return "";
}
}
}
string clientIp = Request.UserHostAddress; // 或解析 X-Forwarded-For
string mac = MacHelper.GetClientMac(clientIp);
Response.Write("Client MAC: " + mac);
輸入 `ip` 參數直接拼接進 `Arguments`,存在**命令注入**風險。生產環境必須驗證 IP 格式(`IPAddress.TryParse`)或使用白名單字符過濾。