Skip to content

Commit

Permalink
Merge pull request #1178 from Mashape/fix/hostname
Browse files Browse the repository at this point in the history
Better get_hostname() implementation
  • Loading branch information
subnetmarco committed Apr 26, 2016
2 parents 5914c01 + 868b7f3 commit 8e059e0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
29 changes: 23 additions & 6 deletions kong/tools/utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
local url = require "socket.url"
local uuid = require "lua_uuid"
local stringy = require "stringy"
local ffi = require "ffi"

local type = type
local pairs = pairs
Expand All @@ -19,17 +20,33 @@ local table_insert = table.insert
local string_find = string.find
local string_format = string.format

local _M = {}
ffi.cdef[[
int gethostname(char *name, size_t len);
]]

local _M = {}

--- Retrieves the hostname of the local machine
-- @return string The hostname
function _M.get_hostname()
local f = io.popen ("/bin/hostname")
local hostname = f:read("*a") or ""
f:close()
hostname = string.gsub(hostname, "\n$", "")
return 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


Expand Down
4 changes: 4 additions & 0 deletions spec/unit/02-utils_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ local utils = require "kong.tools.utils"

describe("Utils", function()

it("should retrieve the hostname", function()
assert.truthy(utils.get_hostname())
end)

describe("string", function()
describe("random_string()", function()
it("should return a random string", function()
Expand Down

0 comments on commit 8e059e0

Please sign in to comment.