/
lua_ip.c
71 lines (57 loc) · 1.59 KB
/
lua_ip.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/***
Generic IP utilities.
@license MIT
@module lua_ip
*/
#include <lua.h>
#include <lauxlib.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <net/if.h>
#if LUA_VERSION_NUM < 502
# define luaL_newlib(L,l) (lua_newtable(L), luaL_register(L,NULL,l))
# define lua_rawlen lua_objlen
#endif
/// Retrieve the first active non loopback IPv4 address
// @return ip_str
// @function get_ip()
static int get_ipv4(lua_State *L) {
struct ifaddrs * ifAddrStruct=NULL;
struct ifaddrs * ifa=NULL;
void * tmpAddrPtr=NULL;
getifaddrs(&ifAddrStruct);
const char * interface = lua_tostring(L, 1);
int found = 0;
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr) {
continue;
}
if (!interface || strcmp(interface, ifa->ifa_name) == 0) {
if ((ifa->ifa_flags & IFF_UP) == 0) continue; // Should be running
if ((ifa->ifa_flags & IFF_LOOPBACK) != 0) continue; // Should not be loopback
if (ifa->ifa_addr->sa_family == AF_INET) { // Should be IPv4
tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
lua_pushstring(L, addressBuffer);
found = 1;
break;
}
}
}
if (!found) {
lua_pushstring(L, NULL);
}
if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
return 1;
}
static const luaL_Reg lua_ip[] = {
{"get_ipv4", get_ipv4},
{NULL, NULL}
};
int luaopen_lua_ip(lua_State *L){
luaL_newlib(L, lua_ip);
return 1;
}