Created
September 25, 2013 20:25
-
-
Save neomantra/6705511 to your computer and use it in GitHub Desktop.
Exercising gethostbyname with LuaJIT FFI
This file contains hidden or 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
#!/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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
very good