Changeset

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
parents 12931:bbae3acc6694
children 12933:3ab0bbb1dc35
files util/ip.lua
diffstat 1 files changed, 12 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/util/ip.lua	Tue Mar 14 18:23:33 2023 +0000
+++ b/util/ip.lua	Tue Mar 14 18:24:58 2023 +0000
@@ -245,10 +245,22 @@
 	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;
 };