2 libloc - A library to determine the location of someone on the Internet
4 Copyright (C) 2024 IPFire Development Team <info@ipfire.org>
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
24 #include <libloc/network.h>
29 typedef struct network
{
30 struct loc_network
* network
;
33 static Network
* luaL_checknetwork(lua_State
* L
, int i
) {
34 void* userdata
= luaL_checkudata(L
, i
, "location.Network");
36 // Throw an error if the argument doesn't match
37 luaL_argcheck(L
, userdata
, i
, "Network expected");
39 return (Network
*)userdata
;
42 int create_network(lua_State
* L
, struct loc_network
* network
) {
43 // Allocate a new object
44 Network
* self
= (Network
*)lua_newuserdata(L
, sizeof(*self
));
47 luaL_setmetatable(L
, "location.Network");
50 self
->network
= loc_network_ref(network
);
55 static int Network_new(lua_State
* L
) {
56 struct loc_network
* network
= NULL
;
61 n
= luaL_checkstring(L
, 1);
64 r
= loc_network_new_from_string(ctx
, &network
, n
);
66 return luaL_error(L
, "Could not create network %s: %s\n", n
, strerror(errno
));
69 r
= create_network(L
, network
);
70 loc_network_unref(network
);
75 static int Network_gc(lua_State
* L
) {
76 Network
* self
= luaL_checknetwork(L
, 1);
80 loc_network_unref(self
->network
);
87 static int Network_tostring(lua_State
* L
) {
88 Network
* self
= luaL_checknetwork(L
, 1);
90 // Push string representation of the network
91 lua_pushstring(L
, loc_network_str(self
->network
));
98 static int Network_get_asn(lua_State
* L
) {
99 Network
* self
= luaL_checknetwork(L
, 1);
101 uint32_t asn
= loc_network_get_asn(self
->network
);
105 lua_pushnumber(L
, asn
);
114 static int Network_get_family(lua_State
* L
) {
115 Network
* self
= luaL_checknetwork(L
, 1);
118 lua_pushnumber(L
, loc_network_address_family(self
->network
));
125 static int Network_get_country_code(lua_State
* L
) {
126 Network
* self
= luaL_checknetwork(L
, 1);
128 const char* country_code
= loc_network_get_country_code(self
->network
);
131 if (country_code
&& *country_code
)
132 lua_pushstring(L
, country_code
);
139 static const struct luaL_Reg Network_functions
[] = {
140 { "new", Network_new
},
141 { "get_asn", Network_get_asn
},
142 { "get_family", Network_get_family
},
143 { "get_country_code", Network_get_country_code
},
144 { "__gc", Network_gc
},
145 { "__tostring", Network_tostring
},
149 int register_network(lua_State
* L
) {
150 return register_class(L
, "location.Network", Network_functions
);