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
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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