ClientInfo.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Management;
  7. using System.Net;
  8. namespace Client
  9. {
  10. public class ClientInfo
  11. {
  12. public string MacAddr { get; set; }
  13. public string Ipv4 { get; set; }
  14. public string Name { get; set; }
  15. }
  16. public class ClientInfoUtil {
  17. /// <summary>
  18. /// 获取本机MAC地址
  19. /// </summary>
  20. /// <returns>本机MAC地址</returns>
  21. public static string GetMacAddress()
  22. {
  23. try
  24. {
  25. string strMac = string.Empty;
  26. ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  27. ManagementObjectCollection moc = mc.GetInstances();
  28. foreach (ManagementObject mo in moc)
  29. {
  30. if ((bool)mo["IPEnabled"] == true)
  31. {
  32. strMac = mo["MacAddress"].ToString();
  33. }
  34. }
  35. moc = null;
  36. mc = null;
  37. return strMac;
  38. }
  39. catch
  40. {
  41. return "unknown";
  42. }
  43. }
  44. /// <summary>
  45. /// 操作系统的登录用户名
  46. /// </summary>
  47. /// <returns>系统的登录用户名</returns>
  48. public static string GetUserName()
  49. {
  50. try
  51. {
  52. string strUserName = string.Empty;
  53. ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
  54. ManagementObjectCollection moc = mc.GetInstances();
  55. foreach (ManagementObject mo in moc)
  56. {
  57. strUserName = mo["UserName"].ToString();
  58. }
  59. moc = null;
  60. mc = null;
  61. return strUserName;
  62. }
  63. catch
  64. {
  65. return "unknown";
  66. }
  67. }
  68. /// <summary>
  69. /// 获取客户端内网IPv4地址
  70. /// </summary>
  71. /// <returns>客户端内网IPv4地址</returns>
  72. public static string GetClientLocalIPv4Address()
  73. {
  74. string strLocalIP = string.Empty;
  75. try
  76. {
  77. IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
  78. IPAddress ipAddress = ipHost.AddressList[0];
  79. strLocalIP = ipAddress.ToString();
  80. return strLocalIP;
  81. }
  82. catch
  83. {
  84. return "unknown";
  85. }
  86. }
  87. }
  88. }