bzp2010 commented on code in PR #12267:
URL: https://github.com/apache/apisix/pull/12267#discussion_r2135250117


##########
t/core/utils.t:
##########
@@ -393,3 +393,24 @@ res:nil
 res:5
 res:12
 res:7
+
+
+
+=== TEST 13: gethostname
+--- config
+    location /t {
+        content_by_lua_block {
+            local core = require("apisix.core")
+            local hostname = core.utils.gethostname()

Review Comment:
   Since the test environment contains `/bin/hostname`, please use the old 
method and the new method to obtain the hostname and compare them here. This 
will help verify whether gethostname is being used correctly.



##########
apisix/core/utils.lua:
##########
@@ -256,19 +260,17 @@ function _M.gethostname()
         return hostname
     end
 
-    local hd = io_popen("/bin/hostname")
-    local data, err = hd:read("*a")
-    if err == nil then
-        hostname = data
-        if string.has_suffix(hostname, "\r\n") then
-            hostname = sub_str(hostname, 1, -3)
-        elseif string.has_suffix(hostname, "\n") then
-            hostname = sub_str(hostname, 1, -2)
-        end
+    local size = 256
+    local buf = ffi_new("unsigned char[?]", size)
+
+    local res = C.gethostname(buf, size)
+    if res == 0 then
+        local data = ffi_string(buf, size)
+        hostname = str_gsub(data, "%z+$", "")
 
     else
         hostname = "unknown"
-        log.error("failed to read output of \"/bin/hostname\": ", err)
+        log.error("gethostname error:", ffi_string(C.strerror(ffi.errno())))

Review Comment:
   Given that this function is not called on the proxy hot path and it has a 
cache, I can also accept the use of `gethostname`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscr...@apisix.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to