openresty 用 gpt 写的获取真实客户端 IP 的代码

-- 检查指定IP是否存在于可信任代理服务器列表中
local function is_trusted_proxy(ip)
    for _, trusted_ip in ipairs(trusted_proxies) do
        if ip == trusted_ip then
            return true
        end
    end
    return false
end
-- 获取真实客户端IP地址
local function get_real_client_ip()
    local x_forwarded_for = ngx.var.http_x_forwarded_for
    local remote_addr = ngx.var.remote_addr

    if not x_forwarded_for or x_forwarded_for == "" then
        return remote_addr
    end

    local ips = {} -- 存储IP地址列表
    for ip in x_forwarded_for:gmatch("%d+%.%d+%.%d+%.%d+") do
        table.insert(ips, ip)
    end

    for i = #ips, 1, -1 do -- 从后往前检查IP地址列表
        if not is_trusted_proxy(ips[i]) then
            return ips[i]
        end
    end

    return remote_addr
end

测试

-- 可信任代理服务器列表
local trusted_proxies = {"2.2.2.2", "3.3.3.3"}
local x_forwarded_for = 'sleep(10),1.1.1.1,2.2.2.2,3.3.3.3'

打印

ips
2023-05-21 18:56:35 [DEBUG] (table)'{
    [1]="1.1.1.1"
    [2]="2.2.2.2"
    [3]="3.3.3.3"
}'
get_real_client_ip()
2023-05-21 18:56:35 [DEBUG] (string)'1.1.1.1'

可信任IP列表支持CIDR的代码

github.com/api7/lua-resty-ipmatche...

local ipmatcher = require  "lib.ipmatcher"

-- 判断指定IP是否在信任代理服务器列表内
local ipm = ipmatcher.new(trusted_proxies)
local function is_trusted_proxy(ip, trusted_proxies)
    return ipm:match(ip)
end
本作品采用《CC 协议》,转载必须注明作者和本文链接
welcome come back
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
95
粉丝
24
喜欢
156
收藏
348
排名:324
访问:2.9 万
私信
所有博文
社区赞助商