IPUtil.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using ERP.Framework.Exceptions;
  2. using ERP.Framework.Resource;
  3. using Microsoft.AspNetCore.Http;
  4. using System.Net;
  5. using System.Net.NetworkInformation;
  6. namespace ERP.Framework.Utils
  7. {
  8. public class IPUtil
  9. {
  10. public static string GetServerIp()
  11. {
  12. var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
  13. foreach (NetworkInterface networkInterface in networkInterfaces)
  14. {
  15. // 过滤掉非活动和环回接口
  16. if (networkInterface.OperationalStatus == OperationalStatus.Up)
  17. {
  18. IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
  19. foreach (UnicastIPAddressInformation ipAddress in ipProperties.UnicastAddresses)
  20. {
  21. // 过滤IPv6地址和保留地址
  22. if (ipAddress.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork &&
  23. !IPAddress.IsLoopback(ipAddress.Address) &&
  24. !ipAddress.Address.IsIPv6LinkLocal &&
  25. !ipAddress.Address.IsIPv6Multicast &&
  26. !ipAddress.Address.IsIPv6SiteLocal &&
  27. !ipAddress.Address.IsIPv6Teredo)
  28. {
  29. return ipAddress.Address.ToString();
  30. }
  31. }
  32. }
  33. }
  34. throw new CodeException(message: FrameworkI18N.NoIP, code: ErrorCode.NO_IP);
  35. }
  36. /// <summary>
  37. /// 获取客户端IP
  38. /// </summary>
  39. /// <returns></returns>
  40. /// <exception cref="Exception"></exception>
  41. public static string GetClientIp()
  42. {
  43. var httpContextAccessor = new HttpContextAccessor();
  44. var httpContext = httpContextAccessor.HttpContext;
  45. var ip = httpContext!.Request.Headers["Cdn-Src-Ip"].FirstOrDefault();
  46. if (!string.IsNullOrEmpty(ip))
  47. return IpReplace(ip);
  48. ip = httpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
  49. if (!string.IsNullOrEmpty(ip))
  50. return IpReplace(ip);
  51. var remoteIpAddress = httpContext.Connection.RemoteIpAddress;
  52. if (remoteIpAddress != null)
  53. {
  54. return remoteIpAddress.ToString();
  55. }
  56. else
  57. {
  58. throw new CodeException(message: FrameworkI18N.NoIP, code: ErrorCode.NO_IP);
  59. }
  60. }
  61. /// <summary>
  62. /// 处理 IPV6
  63. /// </summary>
  64. /// <param name="inip"></param>
  65. /// <returns></returns>
  66. private static string IpReplace(string inip)
  67. {
  68. return inip.Contains("::ffff:") ? inip.Replace("::ffff:", "") : inip;
  69. }
  70. }
  71. }