ClientInfo.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. return $"{Environment.MachineName}\\{Environment.UserName}";
  53. //string strUserName = string.Empty;
  54. //ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
  55. //ManagementObjectCollection moc = mc.GetInstances();
  56. //foreach (ManagementObject mo in moc)
  57. //{
  58. // strUserName = mo["UserName"].ToString();
  59. //}
  60. //moc = null;
  61. //mc = null;
  62. //return strUserName;
  63. }
  64. catch
  65. {
  66. return "unknown";
  67. }
  68. }
  69. /// <summary>
  70. /// 获取客户端内网IPv4地址
  71. /// </summary>
  72. /// <returns>客户端内网IPv4地址</returns>
  73. public static string GetClientLocalIPv4Address()
  74. {
  75. string strLocalIP = string.Empty;
  76. try
  77. {
  78. IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
  79. IPAddress ipAddress = ipHost.AddressList[0];
  80. strLocalIP = ipAddress.ToString();
  81. return strLocalIP;
  82. }
  83. catch
  84. {
  85. return "unknown";
  86. }
  87. }
  88. }
  89. }