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
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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