Skip to content

Instantly share code, notes, and snippets.

@neomantra
Created September 25, 2013 20:25
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save neomantra/6705511 to your computer and use it in GitHub Desktop.
Save neomantra/6705511 to your computer and use it in GitHub Desktop.
Exercising gethostbyname with LuaJIT FFI
#!/usr/bin/luajit
local ffi = require 'ffi'
ffi.cdef([[
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
};
struct hostent *gethostbyname(const char *name);
struct myaddr { uint8_t b1, b2, b3, b4; };
]])
if #arg == 0 then
io.stderr:write('usage: gethost_test hostname [hostname2] [...]\n')
os.exit(-1)
end
for _, name in ipairs(arg) do
local hostent = ffi.C.gethostbyname(tostring(name))
if hostent == nil then
io.stdout:write(name, ': NONE FOUND\n')
else
io.stdout:write(name, ': "', ffi.string(hostent.h_name), '" : [ ')
local i = 0
while i < (hostent.h_length / 4) do
local myaddr = ffi.cast('struct myaddr*', hostent.h_addr_list[i])
io.stdout:write(string.format('%d.%d.%d.%d ',
myaddr.b1, myaddr.b2, myaddr.b3, myaddr.b4))
i = i + 1
end
io.stdout:write(' ]\n')
end
end
@bikong0411
Copy link

very good

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment