@@ -33,15 +33,16 @@ local base = require("resty.core.base")
3333local open = io.open
3434local sub_str = string.sub
3535local str_byte = string.byte
36+ local str_gsub = string.gsub
3637local tonumber = tonumber
3738local tostring = tostring
3839local re_gsub = ngx .re .gsub
3940local re_match = ngx .re .match
4041local re_gmatch = ngx .re .gmatch
4142local type = type
42- local io_popen = io.popen
4343local C = ffi .C
4444local ffi_string = ffi .string
45+ local ffi_new = ffi .new
4546local get_string_buf = base .get_string_buf
4647local exiting = ngx .worker .exiting
4748local ngx_sleep = ngx .sleep
@@ -56,6 +57,8 @@ local max_sleep_interval = 1
5657ffi .cdef [[
5758 int ngx_escape_uri (char * dst , const char * src ,
5859 size_t size , int type );
60+ int gethostname (char * name , size_t len );
61+ char *strerror (int errnum );
5962]]
6063
6164
@@ -256,19 +259,17 @@ function _M.gethostname()
256259 return hostname
257260 end
258261
259- local hd = io_popen (" /bin/hostname" )
260- local data , err = hd :read (" *a" )
261- if err == nil then
262- hostname = data
263- if string .has_suffix (hostname , " \r\n " ) then
264- hostname = sub_str (hostname , 1 , - 3 )
265- elseif string .has_suffix (hostname , " \n " ) then
266- hostname = sub_str (hostname , 1 , - 2 )
267- end
262+ local size = 256
263+ local buf = ffi_new (" unsigned char[?]" , size )
264+
265+ local res = C .gethostname (buf , size )
266+ if res == 0 then
267+ local data = ffi_string (buf , size )
268+ hostname = str_gsub (data , " %z+$" , " " )
268269
269270 else
270271 hostname = " unknown"
271- log .error (" failed to read output of \" /bin/hostname \" : " , err )
272+ log .error (" failed to call gethostname() : " , ffi_string ( C . strerror ( ffi . errno ())) )
272273 end
273274
274275 return hostname
0 commit comments