Created
June 14, 2016 04:33
-
-
Save bikong0411/ba75f6fee34327a060135e2cb04f3ee3 to your computer and use it in GitHub Desktop.
常用lua的功能函数
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
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); | |
int gethostname(char *name, size_t len); | |
struct myaddr { uint8_t b1, b2, b3, b4; }; | |
]] | |
local _M = {} | |
function _M.get_hostname() | |
local result | |
local C = ffi.C | |
local SIZE = 128 | |
local buf = ffi.new("unsigned char[?]", SIZE) | |
local res = C.gethostname(buf, SIZE) | |
if res == 0 then | |
local hostname = ffi.string(buf, SIZE) | |
result = string.gsub(hostname, "%z+$", "") | |
else | |
local f = io.popen ("/bin/hostname") | |
local hostname = f:read("*a") or "" | |
f:close() | |
result = string.gsub(hostname, "\n$", "") | |
end | |
return result | |
end | |
function _M.gethostbyname(hostname) | |
local hostent = ffi.C.gethostbyname(tostring(hostname)) | |
if hostent == nil then | |
return 'Not Found' | |
else | |
local result = '"' .. 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]) | |
result = result .. string.format('%d.%d.%d.%d ',myaddr.b1, myaddr.b2, myaddr.b3, myaddr.b4) | |
i = i + 1 | |
end | |
result = result .. ']' | |
return result | |
end | |
end | |
return _M |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment