aboutsummaryrefslogtreecommitdiffstats
path: root/util
diff options
context:
space:
mode:
authorMatthew Wild <mwild1@gmail.com>2023-03-14 18:24:58 +0000
committerMatthew Wild <mwild1@gmail.com>2023-03-14 18:24:58 +0000
commit84c0204ea252f2464637de99a69bb87bce5b382a (patch)
treed295aec5d80babec6f8be6003fb815032216f70e /util
parent3eedf79c8bd6555ebe601c67942af07aff3782a1 (diff)
downloadprosody-84c0204ea252f2464637de99a69bb87bce5b382a.tar.gz
prosody-84c0204ea252f2464637de99a69bb87bce5b382a.zip
util.ip: Add ip.truncate() to return a new IP with only the prefix of another
Diffstat (limited to 'util')
-rw-r--r--util/ip.lua12
1 files changed, 12 insertions, 0 deletions
diff --git a/util/ip.lua b/util/ip.lua
index 5e20febe..cd304342 100644
--- a/util/ip.lua
+++ b/util/ip.lua
@@ -245,10 +245,22 @@ local function is_ip(obj)
return getmetatable(obj) == ip_mt;
end
+local function truncate(ip, n_bits)
+ if n_bits % 8 ~= 0 then
+ return error("ip.truncate() only supports multiples of 8 bits");
+ end
+ local n_octets = n_bits / 8;
+ if not is_ip(ip) then
+ ip = new_ip(ip);
+ end
+ return new_ip(net.ntop(ip.packed:sub(1, n_octets)..("\0"):rep(#ip.packed-n_octets)))
+end
+
return {
new_ip = new_ip,
commonPrefixLength = commonPrefixLength,
parse_cidr = parse_cidr,
match = match,
is_ip = is_ip;
+ truncate = truncate;
};