From a457e5e59fec0694893e4b19f7d91d13d637ac82 Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Sat, 6 Apr 2024 11:11:28 +0000 Subject: [PATCH] lua: Add function that returns subnets of a network Signed-off-by: Michael Tremer --- src/lua/network.c | 31 +++++++++++++++++++++++++++++++ tests/lua/main.lua | 18 ++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/src/lua/network.c b/src/lua/network.c index 15936f7..2da6a1d 100644 --- a/src/lua/network.c +++ b/src/lua/network.c @@ -151,6 +151,36 @@ static int Network_has_flag(lua_State* L) { return 1; } +// Subnets + +static int Network_subnets(lua_State* L) { + struct loc_network* subnet1 = NULL; + struct loc_network* subnet2 = NULL; + int r; + + Network* self = luaL_checknetwork(L, 1); + + // Make subnets + r = loc_network_subnets(self->network, &subnet1, &subnet2); + if (r) + return luaL_error(L, "Could not create subnets of %s: %s\n", + loc_network_str(self->network), strerror(errno)); + + // Create a new table + lua_createtable(L, 2, 0); + + // Create the networks & push them onto the table + create_network(L, subnet1); + loc_network_unref(subnet1); + lua_rawseti(L, -2, 1); + + create_network(L, subnet2); + loc_network_unref(subnet2); + lua_rawseti(L, -2, 2); + + return 1; +} + // Reverse Pointer static int Network_reverse_pointer(lua_State* L) { @@ -188,6 +218,7 @@ static const struct luaL_Reg Network_functions[] = { { "get_family", Network_get_family }, { "has_flag", Network_has_flag }, { "reverse_pointer", Network_reverse_pointer }, + { "subnets", Network_subnets }, { "__gc", Network_gc }, { "__tostring", Network_tostring }, { NULL, NULL }, diff --git a/tests/lua/main.lua b/tests/lua/main.lua index b45ab1c..e139b2d 100755 --- a/tests/lua/main.lua +++ b/tests/lua/main.lua @@ -151,6 +151,24 @@ function test_gc() print("GC: " .. collectgarbage("collect")) end +function test_subnets() + location = require("location") + + -- Open the database + db = location.Database.open(ENV_TEST_DATABASE) + + local network = db:lookup("1.1.1.1") + + local subnets = network:subnets() + + luaunit.assertIsTable(subnets) + luaunit.assertEquals(#subnets, 2) + + for i, subnet in ipairs(subnets) do + print(subnet) + end +end + function test_list_networks() location = require("location") -- 2.39.2