123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- using ERP.Framework.Exceptions;
- using ERP.Framework.Resource;
- using Microsoft.AspNetCore.Http;
- using System.Net;
- using System.Net.NetworkInformation;
- namespace ERP.Framework.Utils
- {
- public class IPUtil
- {
- public static string GetServerIp()
- {
- var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
- foreach (NetworkInterface networkInterface in networkInterfaces)
- {
- // 过滤掉非活动和环回接口
- if (networkInterface.OperationalStatus == OperationalStatus.Up)
- {
- IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
- foreach (UnicastIPAddressInformation ipAddress in ipProperties.UnicastAddresses)
- {
- // 过滤IPv6地址和保留地址
- if (ipAddress.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork &&
- !IPAddress.IsLoopback(ipAddress.Address) &&
- !ipAddress.Address.IsIPv6LinkLocal &&
- !ipAddress.Address.IsIPv6Multicast &&
- !ipAddress.Address.IsIPv6SiteLocal &&
- !ipAddress.Address.IsIPv6Teredo)
- {
- return ipAddress.Address.ToString();
- }
- }
- }
- }
- throw new CodeException(message: FrameworkI18N.NoIP, code: ErrorCode.NO_IP);
- }
- /// <summary>
- /// 获取客户端IP
- /// </summary>
- /// <returns></returns>
- /// <exception cref="Exception"></exception>
- public static string GetClientIp()
- {
- var httpContextAccessor = new HttpContextAccessor();
- var httpContext = httpContextAccessor.HttpContext;
- var ip = httpContext!.Request.Headers["Cdn-Src-Ip"].FirstOrDefault();
- if (!string.IsNullOrEmpty(ip))
- return IpReplace(ip);
- ip = httpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
- if (!string.IsNullOrEmpty(ip))
- return IpReplace(ip);
- var remoteIpAddress = httpContext.Connection.RemoteIpAddress;
- if (remoteIpAddress != null)
- {
- return remoteIpAddress.ToString();
- }
- else
- {
- throw new CodeException(message: FrameworkI18N.NoIP, code: ErrorCode.NO_IP);
- }
- }
- /// <summary>
- /// 处理 IPV6
- /// </summary>
- /// <param name="inip"></param>
- /// <returns></returns>
- private static string IpReplace(string inip)
- {
- return inip.Contains("::ffff:") ? inip.Replace("::ffff:", "") : inip;
- }
- }
- }
|