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);
}
///
/// 获取客户端IP
///
///
///
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);
}
}
///
/// 处理 IPV6
///
///
///
private static string IpReplace(string inip)
{
return inip.Contains("::ffff:") ? inip.Replace("::ffff:", "") : inip;
}
}
}