根据ip地址获取mac地址的方法网上有很多,但是由于路由器的关系,只能局限于获取同网段的ip的mac地址,后来知道了一个dos命令"nbtstat",这个命令就可以跨网段获取mac,不过测试过有一些地址还是获取不了,好像开了防火墙就不行,后来找到一段代码,原理就是根据这个命令获取返回的数据然后用正则表达式进行mac信息段的截取,如下:
//通过IP地址获取MAC地址的方法(可跨网段获取)
string GetMac(string IP)
{
string dirResults = "";
ProcessStartInfo psi = new ProcessStartInfo();
Process proc = new Process();
psi.FileName = "nbtstat";
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.Arguments = "-A " + IP;
psi.UseShellExecute = false;
proc = Process.Start(psi);
dirResults = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
dirResults = dirResults.Replace("\r", "").Replace("\n", "").Replace("\t", "");
Regex reg = new Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?<key>((.)*?))__MAC", RegexOptions.IgnoreCase | RegexOptions.Compiled);
Match mc = reg.Match(dirResults + "__MAC");
if (mc.Success)
{ return mc.Groups["key"].Value; }
else
{
reg = new Regex("Host not found", RegexOptions.IgnoreCase | RegexOptions.Compiled);
mc = reg.Match(dirResults);
if (mc.Success)
{
return "Host not found!";
}
else
{ return ""; }
}
}
asp.net中调用如下:
//获取客户端ip地址
string ipAddress = Request.UserHostAddress.ToString().Trim();
//调用函数得到mac地址
string macAddress = GetMac(ipAddress);