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 协议》,转载必须注明作者和本文链接