[c-sharp] view plaincopy
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.UI;
6. using System.Web.UI.WebControls;
7. //添加引用,并导入命名空间
8. using System.Management;
9. namespace WebApp
10. {
11. public partial class WebForm1 : System.Web.UI.Page
12. {
13. protected void Page_Load(object sender, EventArgs e)
14. {
15. Response.Write("计算机名称: " + System.Net.Dns.GetHostName() + "<br>");
16. //调用GetMacAddress函数,获取网卡地址信息
17. Response.Write("MAC地址: " + GetMacAddress());
18. }
19. /// <summary>
20. /// 获取网卡地址信息
21. /// </summary>
22. /// <returns></returns>
23. string GetMacAddress()
24. {
25. try
26. {
27. string mac = "";
28. ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
29. ManagementObjectCollection moc = mc.GetInstances();
30. foreach (ManagementObject mo in moc)
31. {
32. if ((bool)mo["IPEnabled"] == true)
33. {
34. mac = mo["MacAddress"].ToString();
35. break;
36. }
37. }
38. moc = null;
39. mc = null;
40. return mac;
41. }
42. catch
43. {
44. return "unknow";
45. }
46. }
47. }
48. }
运行结果:
计算机名称: lenovo-05d886ff
MAC地址: 00:26:22:05:8C:C7
注意:上传到服务器测试,发现获得的是服务器的MAC地址
方式二:通过win32特性获得
优点:无需在客户端设置;
缺点:无法获取服务器的mac(经测试总为0,其实感觉没有必要获取服务器的mac,所以也不算缺点)(能否跨网段获取还没有测试)
[c-sharp] view plain