Software /
code /
prosody
Comparison
util/ip.lua @ 12932:9bb044705ea1
util.ip: Add ip.truncate() to return a new IP with only the prefix of another
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Tue, 14 Mar 2023 18:24:58 +0000 |
parent | 12931:bbae3acc6694 |
child | 12975:d10957394a3c |
comparison
equal
deleted
inserted
replaced
12931:bbae3acc6694 | 12932:9bb044705ea1 |
---|---|
243 | 243 |
244 local function is_ip(obj) | 244 local function is_ip(obj) |
245 return getmetatable(obj) == ip_mt; | 245 return getmetatable(obj) == ip_mt; |
246 end | 246 end |
247 | 247 |
248 local function truncate(ip, n_bits) | |
249 if n_bits % 8 ~= 0 then | |
250 return error("ip.truncate() only supports multiples of 8 bits"); | |
251 end | |
252 local n_octets = n_bits / 8; | |
253 if not is_ip(ip) then | |
254 ip = new_ip(ip); | |
255 end | |
256 return new_ip(net.ntop(ip.packed:sub(1, n_octets)..("\0"):rep(#ip.packed-n_octets))) | |
257 end | |
258 | |
248 return { | 259 return { |
249 new_ip = new_ip, | 260 new_ip = new_ip, |
250 commonPrefixLength = commonPrefixLength, | 261 commonPrefixLength = commonPrefixLength, |
251 parse_cidr = parse_cidr, | 262 parse_cidr = parse_cidr, |
252 match = match, | 263 match = match, |
253 is_ip = is_ip; | 264 is_ip = is_ip; |
265 truncate = truncate; | |
254 }; | 266 }; |