From 9edfd0002bea4d591cb363be536c652ef3f16079 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Sloth=20T=C3=B8nnesen?= Date: Sat, 20 Jul 2019 18:19:38 +0000 Subject: add inet:subnets() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Asbjørn Sloth Tønnesen --- lua/inet/core.lua | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'lua/inet/core.lua') diff --git a/lua/inet/core.lua b/lua/inet/core.lua index f1c7c49..15dd0f9 100644 --- a/lua/inet/core.lua +++ b/lua/inet/core.lua @@ -6,6 +6,7 @@ local format = string.format local floor = math.floor local min = math.min local max = math.max +local pow = math.pow local insert = table.insert local lshift = bit32.lshift @@ -55,6 +56,16 @@ end inet4.__len = inet.__len inet6.__len = inet.__len +function inet:subnets(n) + if type(n) ~= 'number' then return nil, 'n must be a number' end + local hostmask = is_inet6(self) and 128 or 32 + if n < 0 or n > hostmask then return nil, 'invalid mask given' end + local mask = self.mask + local bits = n - mask + local subnets = pow(2, bits) + return subnets +end + function inet:family() local mt = assert(getmetatable(self)) return assert(mt2fam[mt]) @@ -329,7 +340,7 @@ function inet4:__sub(n) end function inet4:__mul(n) - local new = self.bip + (n * math.pow(2, 32 - self.mask)) + local new = self.bip + (n * pow(2, 32 - self.mask)) return new_inet4(new, self.mask) end -- cgit v1.2.1