asp.net获取mac(终)

经测试成功 只能获取同网段的哦~

顺便奉送

asp.net 获取服务器的硬盘id 网卡mac地址 cpu序列号

多个IP、端口、MAC地址的正则匹配

js获取mac地址(续)

记得引用using System.Runtime.InteropServices;

 [DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);

///<summary>
///得到客户端ip
///</summary>
///<returns>ip</returns>
private string GetClientIP()
{
string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (null == result || result == String.Empty)
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (null == result || result == String.Empty)
{
result = HttpContext.Current.Request.UserHostAddress;
}
return result;
}


///<summary>
/// 利用客户端ip得到客户端mac
///</summary>
///<param name="remoteip">客户端ip</param>
///<returns>int16类型的mac</returns>
static private Int64 getremotemac(string remoteip)
{
Int32 ldest = inet_addr(remoteip);
try
{
Int64 macinfo = new Int64();
Int32 len = 6;
int res = SendARP(ldest, 0, ref macinfo, ref len);
return macinfo;
}
catch (Exception err)
{
Console.WriteLine("error:{0}", err.Message);
}
return 0;
}


///<summary>
/// int64类型的mac转换成正确的客户端mac
///</summary>
///<returns>mac</returns>
private string GetClientMAC()
{
Int64 macid = getremotemac(GetClientIP());
if (macid == 0)
return "0";
string beforeMacAddr = Convert.ToString(macid, 16);
string endMacAddr = "";
string[] macArray = new string[6];
for (int i = 0; i < 6; i++)
{
macArray[i] = beforeMacAddr.Substring(i * 2, 2);
}
for (int i = 0; i < 6; i++)
{
endMacAddr += macArray[5 - i] + "-";
}
endMacAddr = endMacAddr.Substring(0, endMacAddr.Length - 1);
endMacAddr = endMacAddr.ToUpper();
return endMacAddr;
}



posted @ 2011-11-02 17:13  一个土豆一棵青菜  阅读(10567)  评论(1编辑  收藏  举报