代码如下:
#region 获取IP地址和Mac地址
[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地址和Mac地址
/// </summary>
/// <param name="page">page为页面对象引用(赋值为:this.Page)</param>
/// <param name="IP">输出IP地址到变量“IP”</param>
/// <param name="Mac">输出Mac地址到变量“Mac”</param>
/// <returns>是否执行成功</returns>
public static bool AcquireIPAndMac(Page page, out string IP,out string Mac)
{
try
{
string userip =page.Request.UserHostAddress;
string strClientIP = page.Request.UserHostAddress.ToString().Trim();
Int32 ldest = inet_addr(strClientIP); //目的地的ip
Int64 macinfo = new Int64();
Int32 len = 6;
int res = SendARP(ldest, 0, ref macinfo, ref len);
string mac_src = macinfo.ToString("X");
if (mac_src == "0")
{
IP = "";
Mac = "";
return false;
}
while (mac_src.Length < 12)
{
mac_src = mac_src.Insert(0, "0");
}
string mac_dest = "";
for (int i = 0; i < 11; i++)
{
if (0 == (i % 2))
{
if (i == 10)
{
mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
}
else
{
mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
}
}
}
Mac = mac_dest;
IP = userip;
return true;
}
catch (Exception err)
{
page.Response.Write("<script language='Javascript'>"+err.Message.ToString()+"</script>");
}
IP = "";
Mac = "";
return false;
}
#endregion