我在近期项目里面去记录异常日志时,用到了这两个地址,也是从网上和前辈那里学习到的,本人项目是MVC框架的,自己整理了一个公共方法类,包括获取远程客户端IP和Mac地址,以及获取本机Mac地址的方法,代码如下:

1 using System; 2 using System.Management; 3 using System.Runtime.InteropServices; 4 using System.Web; 5 6 namespace St_Te.Ultity 7 { 8 /// <summary> 9 /// 获取IP和Mac地址的方法类 10 /// </summary> 11 public class GetIPandMac 12 { 13 /// <summary> 14 /// 获取客户端IP地址 15 /// </summary> 16 public static string GetIP() 17 { 18 return HttpContext.Current.Request.UserHostAddress; 19 } 20 21 /// <summary> 22 /// 获取本机Mac地址 23 /// </summary> 24 /// <returns></returns> 25 public static string GetMac() 26 { 27 ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); 28 29 ManagementObjectCollection mocollection = mc.GetInstances(); 30 31 foreach (ManagementObject mo in mocollection) 32 { 33 if ((bool)mo["IPEnabled"] == true) 34 { 35 var mac = mo["MacAddress"].ToString(); 36 mo.Dispose(); 37 return mac; 38 } 39 } 40 return ""; 41 } 42 43 44 [DllImport("Iphlpapi.dll")] 45 private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length); 46 [DllImport("Ws2_32.dll")] 47 private static extern Int32 inet_addr(string ip); 48 49 /// <summary> 50 /// 获取客户端Mac地址 51 /// </summary> 52 /// <returns></returns> 53 public static string GetClientMAC() 54 { 55 string mac = string.Empty; 56 // 在此处放置用户代码以初始化页面 57 try 58 { 59 if (HttpContext.Current.Request.UserHostAddress != null) 60 { 61 string strClientIP = HttpContext.Current.Request.UserHostAddress.Trim(); 62 int ldest = inet_addr(strClientIP); //目的地的ip 63 inet_addr(""); 64 long macinfo = new Int64(); 65 int len = 6; 66 SendARP(ldest, 0, ref macinfo, ref len); 67 string macSrc = macinfo.ToString("X"); 68 while (macSrc.Length < 12) 69 { 70 macSrc = macSrc.Insert(0, "0"); 71 } 72 for (int i = 0; i < 11; i++) 73 { 74 if (0 == (i % 2)) 75 { 76 if (i == 10) 77 { 78 mac = mac.Insert(0, macSrc.Substring(i, 2)); 79 } 80 else 81 { 82 mac = "-" + mac.Insert(0, macSrc.Substring(i, 2)); 83 } 84 85 } 86 } 87 } 88 } 89 catch (Exception ex) 90 { 91 throw ex; 92 } 93 return mac; 94 } 95 } 96 }
说明一下,获取IP地址的方法,如果直接在controller里面获取,则这样写:
var ip = Request.UserHostAddress;
获取Mac地址的方法里引用了ManagementClass类,需要添加System.Management.dll的引用。
ManageMentClass 对象被实例化时,根据初始化参数的不同能够获取不同的本地信息:
"Win32_NetworkAdapterConfiguration" 获取本机网络适配器对象。据此可以获取网络地址等。
"Win32_DiskDiver" 获取本机硬盘的相关信息,
"Win32_Processor" 获取本机CPU相关的信息。
"Win32_OperatingSystem" 获取内存等相关信息。
/***************************我是可爱的分割线*******************************/