diff options
author | Matthew Wild <mwild1@gmail.com> | 2023-03-14 18:24:58 +0000 |
---|---|---|
committer | Matthew Wild <mwild1@gmail.com> | 2023-03-14 18:24:58 +0000 |
commit | 84c0204ea252f2464637de99a69bb87bce5b382a (patch) | |
tree | d295aec5d80babec6f8be6003fb815032216f70e /util/ip.lua | |
parent | 3eedf79c8bd6555ebe601c67942af07aff3782a1 (diff) | |
download | prosody-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/ip.lua')
-rw-r--r-- | util/ip.lua | 12 |
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; }; |