获取客户端IP地址

/// <summary>
/// Ip地址实现
/// </summary>
public class IpAddressHelper : IIpAddressHelper
{
    /// <summary>
    /// IHttpContextAccessor
    /// </summary>
    private readonly IHttpContextAccessor _httpContextAccessor;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="httpContextAccessor">IHttpContextAccessor</param>
    public IpAddressHelper(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    /// <summary>
    /// 获取IP地址
    /// </summary>
    /// <returns>Ip地址</returns>
    public string GetIpAddress()
    {
        var request = _httpContextAccessor.HttpContext.Request;
        var ip = string.Empty;
        if (string.IsNullOrEmpty(ip) && request.Headers.TryGetValue("X-Forwarded-For", out var ip1))
        {
            ip = ip1;
        }
        else if (string.IsNullOrEmpty(ip) && request.Headers.TryGetValue("Proxy-Client-Ip", out var ip2))
        {
            ip = ip2;
        }
        else if (string.IsNullOrEmpty(ip) && request.Headers.TryGetValue("wL-Proxy-Client-Ip", out var ip3))
        {
            ip = ip3;
        }
        else if (string.IsNullOrEmpty(ip) && request.Headers.TryGetValue("HTTP CLIENT IP", out var ip4))
        {
            ip = ip4;
        }
        else if (string.IsNullOrEmpty(ip) && request.Headers.TryGetValue("HTTP X FORWARDED FOR", out var ip5))
        {
            ip = ip5;
        }
        else
        {
            ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
        }
        // 处理IPv6地址映射到IPv4的情况
        if (ip.Contains(":") && ip.Contains("%"))
        {
            ip = ip.Split('%')[0];
        }
        return ip;
    }
}

  

posted @ 2024-05-28 16:53  刘小吉  阅读(19)  评论(0编辑  收藏  举报