Created
May 9, 2012 14:37
-
-
Save neomantra/2644943 to your computer and use it in GitHub Desktop.
ifaddrs FFI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ffi.cdef([[ | |
struct ifaddrs { | |
struct ifaddrs *ifa_next; /* Next item in list */ | |
char *ifa_name; /* Name of interface */ | |
unsigned int ifa_flags; /* Flags from SIOCGIFFLAGS */ | |
struct sockaddr *ifa_addr; /* Address of interface */ | |
struct sockaddr *ifa_netmask; /* Netmask of interface */ | |
union { | |
struct sockaddr *ifu_broadaddr; /* Broadcast address of interface */ | |
struct sockaddr *ifu_dstaddr; /* Point-to-point destination address */ | |
} ifa_ifu; | |
void *ifa_data; /* Address-specific data */ | |
}; | |
// the union will be populated based on the following ifa_flags: | |
enum { | |
IFF_BROADCAST = 0x2, /* broadcast address valid */ | |
IFF_POINTOPOINT = 0x10 /* interface is has p-p link */ | |
}; | |
int getifaddrs(struct ifaddrs **ifap); | |
void freeifaddrs(struct ifaddrs *ifa); | |
]]) | |
-- Returns a Lua array of interfaces retrieved via C.getifaddrs | |
-- The original ifaddrs linked list is stored in ret.ifaddrs and is freed upon GC of ret | |
local function getifaddrs() | |
local ifaddrs_root = ffi.new("struct ifaddrs *[1]") | |
local res = C.getifaddrs( ifaddrs_root ) | |
assert( res == 0, ffi.errno() ) | |
-- convert linked list to Lua array for convenience | |
local tret = {} | |
local iter = ifaddrs_root[0] | |
while iter ~= nil do | |
tret[#tret + 1] = iter | |
iter = iter.ifa_next | |
end | |
-- free ifaddrs when tret is gc'd | |
tret.ifaddrs = ifaddrs_root | |
ffi.gc( ifaddrs_root, function(t) C.freeifaddrs(t[0]) end ) | |
return tret | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment