1
0

IPHelper.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using Microsoft.AspNetCore.Http;
  2. using System.Linq;
  3. using System.Net.NetworkInformation;
  4. using System.Text.RegularExpressions;
  5. namespace Admin.Core.Common.Helpers
  6. {
  7. public class IPHelper
  8. {
  9. /// <summary>
  10. /// 是否为ip
  11. /// </summary>
  12. /// <param name="ip"></param>
  13. /// <returns></returns>
  14. public static bool IsIP(string ip)
  15. {
  16. return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
  17. }
  18. /// <summary>
  19. /// 获得IP地址
  20. /// </summary>
  21. /// <param name="request"></param>
  22. /// <returns></returns>
  23. public static string GetIP(HttpRequest request)
  24. {
  25. if (request == null)
  26. {
  27. return "";
  28. }
  29. string ip = request.Headers["X-Real-IP"].FirstOrDefault();
  30. if (ip.IsNull())
  31. {
  32. ip = request.Headers["X-Forwarded-For"].FirstOrDefault();
  33. }
  34. if (ip.IsNull())
  35. {
  36. ip = request.HttpContext?.Connection?.RemoteIpAddress?.ToString();
  37. }
  38. if (ip.IsNull() || !IsIP(ip.Split(":")[0]))
  39. {
  40. ip = "127.0.0.1";
  41. }
  42. return ip;
  43. }
  44. /// <summary>
  45. /// 获得MAC地址
  46. /// </summary>
  47. /// <returns></returns>
  48. public static string GetMACIp()
  49. {
  50. //本地计算机网络连接信息
  51. //IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
  52. //获取本机电脑名
  53. //var HostName = computerProperties.HostName;
  54. //获取域名
  55. //var DomainName = computerProperties.DomainName;
  56. //获取本机所有网络连接
  57. NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
  58. if (nics == null || nics.Length < 1)
  59. {
  60. return "";
  61. }
  62. var MACIp = "";
  63. foreach (NetworkInterface adapter in nics)
  64. {
  65. var adapterName = adapter.Name;
  66. var adapterDescription = adapter.Description;
  67. var NetworkInterfaceType = adapter.NetworkInterfaceType;
  68. if (adapterName == "本地连接" || adapterName == "WLAN")
  69. {
  70. PhysicalAddress address = adapter.GetPhysicalAddress();
  71. byte[] bytes = address.GetAddressBytes();
  72. for (int i = 0; i < bytes.Length; i++)
  73. {
  74. MACIp += bytes[i].ToString("X2");
  75. if (i != bytes.Length - 1)
  76. {
  77. MACIp += "-";
  78. }
  79. }
  80. }
  81. }
  82. return MACIp;
  83. }
  84. }
  85. }