在 OpenResty 中,可以直接使用 Lua 的 socket
库(如 luasocket
)或 OpenResty 自带的 resty.socket
模块来比较两个 IP 地址(IPv4/IPv6)。以下是两种实现方式:
方法1:使用 LuaSocket(纯 Lua)
LuaSocket 提供了 socket.dns.toip
和 socket.ip
功能,可以解析和标准化 IP 地址。
步骤
安装 LuaSocket(如果尚未安装):
luarocks install luasocket
代码实现:
local socket = require("socket")
-- 比较两个IP是否相等(支持IPv4/IPv6)
local function compare_ips(ip1, ip2)
-- 尝试解析为IPv4或IPv6格式
local ip1_normalized = socket.dns.toip(ip1) or ip1
local ip2_normalized = socket.dns.toip(ip2) or ip2
-- IPv6可能有多重表示法(如 ::1 == 0:0:0:0:0:0:0:1),需进一步处理
if ip1_normalized == "::ffff:" .. ip2_normalized then
return true -- IPv4-mapped IPv6格式兼容性检查
end
return ip1_normalized == ip2_normalized
end
-- 测试用例
print(compare_ips("192.168.1.1", "192.168.001.001")) --> true (IPv4)
print(compare_ips("2001:db8::1", "2001:0db8::0001")) --> true (IPv6缩写标准化)
print(compare_ips("::ffff:192.168.0.1", "192.168.0.1")) --> true (IPv4-mapped IPv6)
方法2:使用 OpenResty 的 resty.socket.tcp
OpenResty内置的 resty.socket.tcp
模块虽然没有直接提供IP比较功能,但可以通过以下方式实现:
local sock = require("resty.socket.tcp")
-- OpenResty环境下更推荐用 ngx.re.match + IP正则匹配
local function is_same_ip(ip1, ip2)
-- IPv4正则匹配(简化版)
if ngx.re.match(ip1, [[^\d+\.\d+\.\d+\.\d+$]]) and
ngx.re.match(ip2, [[^\d+\.\d+\.\d+\.\d+$]]) then
return ip1 == ip2 --直接比较字符串形式的IPv4
end
-- IPv6正则匹配(简化版)
if ngx.re.match(ip1, [[^[a-fA-F0-9:]+$]]) and
ngx.re.match(ip2, [[^[a-fA-F0-9:]+$]]) then
-- TODO:此处应添加IPv6标准化逻辑(如展开缩写)
return string.lower(ip1) == string.lower(ip2)
end
return false --协议不匹配或无效IP
end
--示例用法:
ngx.say(is_same_ip("2001:db8::", "20010DB80000::")) --> false (需先标准化!)
关键注意事项
IPv6标准化问题
- IPv6地址可能有多种合法表示形式(例如
20010DB80000::/64
vs20010DB80000000000000000000000000/64
)。 - 解决方案:使用第三方库如
lua-resty-iputils
,或手动展开缩写:
local function expand_ipv6(ip)
-- TODO:实现将 ::ffff:a.b.c.d转换为标准格式的逻辑
end
性能优化
- 避免频繁解析:对高频比较的场景,建议预先把IP解析为二进制格式存储。
- 缓存结果:使用共享字典 (
ngx.shared.DICT
)缓存已解析的IP。
最终推荐方案
虽然可以用socket
库实现,但在OpenResty环境下强烈推荐直接用 lua-resty-iputils
:
local iputils = require "resty.iputils"
if iputils.parse_ip("20010DB80000::") == iputils.parse_ip("20010DB80000...") then ... end
理由:
- ✅自动处理所有IP格式标准化
- ✅无需额外依赖
- ✅性能更高
内容由零声教学AI助手提供,问题来源于学员提问