High-performance IP address matching for OpenResty Lua.
location / {
content_by_lua_block {
local ipmatcher = require("resty.ipmatcher")
local ip = ipmatcher.new({
"127.0.0.1",
"192.168.0.0/16",
"::1",
"fe80::/32",
})
ngx.say(ip:match("127.0.0.1"))
ngx.say(ip:match("192.168.1.100"))
ngx.say(ip:match("::1"))
}
}Creates a new hash table to store IP addresses.
ips is a list of IPv4 or IPv6 IP addresses in a CIDR format ({ip1, ip2, ip3, ...}).
ok, err = ipmatcher.new(ips)Returns nil and the error if it fails to create a new ipmatcher instance.
local ip, err = ipmatcher.new({
"127.0.0.1", "192.168.0.0/16", "::1", "fe80::/16",
})Creates a new hash table to store IP addresses and corresponding values.
ips is a list of key-value pairs ({[ip1] = val1, [ip2] = val2, ...}), where each key is an IP address string (CIDR format for IPv4 and IPv6).
matcher, err = ipmatcher.new_with_value(ips)Returns nil and the error if it fails to create a new ipmatcher instance.
local ip, err = ipmatcher.new_with_value({
["127.0.0.1"] = {info = "a"},
["192.168.0.0/16"] = {info = "b"},
})
local data, err = ip:match("192.168.0.1")
print(data.info) -- "b"If the IP address matches multiple values, the returned value can be either one of the values:
local ip, err = ipmatcher.new_with_value({
["192.168.0.1"] = {info = "a"},
["192.168.0.0/16"] = {info = "b"},
})
local data, err = ip:match("192.168.0.1")
print(data.info) -- "a" or "b"Checks if an IP address exists in the specified IP list.
ip is an IP address string.
ok, err = ip:match(ip)Returns true or value if the specified ip exists in the list. Returns false if the ip does not exist in the list. And returns false and an error message if the IP address is invalid.
local ip, err = ipmatcher.new({
"127.0.0.1", "192.168.0.0/16", "::1", "fe80::/16",
})
local ok, err = ip:match("127.0.0.1") -- trueChecks if an IP address in binary format exists in the specified IP list.
bin_ip is an IP address in binary format.
ok, err = ip:match_bin(bin_ip)Returns true if the specified bin_ip exists in the list. Returns false if it does not exist. Returns nil and an error message if bin_ip is invalid.
local ok, err = ip:match_bin(ngx.var.binary_remote_addr)Tries to parse an IPv4 address to a host byte order FFI uint32_t type integer.
ipmatcher.parse_ipv4(ip)Returns false if the IP address is invalid.
Tries to parse an IPv6 address to a table with four host byte order FF1 uint32_t type integer. The IP address can be wrapped in square brackets like [::1].
ipmatcher.parse_ipv6(ip)Returns a false if the ip is not a valid IPv6 address.
luarocks install lua-resty-ipmatchermake install