Module to get IP address, port and label of a server

This came as a question today.  This following code could be done using python in Iguana 4, it’s just a whole lot easier with the Translator to write the same logic in Lua.

This module does the following:

  • Invokes ipconfig using popen and picks out the IPv4 address of the server.
  • Opens and parses IguanaConfiguration.xml to get the port and optional label for the server.

The above screen shot shows good usage of this module – we invoke server.Info() just one time when the script is first executed. The function returns a Lua table of the information about the server. In this case the server label was set to Training.

Other good techniques for getting server information are to look at environmental variables which you can obtain via os.getenv() in Lua.

Here’s the source code for the module:

server = {}

local function ReadFile(FileName)
   local F = io.open(FileName)
   local X = F:read("*all")
   F:close()
   return X
end

function GetServer()
   local X = ReadFile('IguanaConfiguration.xml')
   X = xml.parse{data=X}
   local L=''
   if X.iguana_config.web_config:childCount('server_label') > 0 then
      L = X.iguana_config.web_config.server_label:nodeValue()
   end  
   return L, X.iguana_config.web_config.port:nodeValue()
end

local function GetHost()
   local F,L,IP
   F = io.popen('ipconfig')
   L = F:read("*all")
   F:close()
   IP = L:match('IP Address.*: (%d*.%d*.%d*.%d*).*Sub')
   if not IP then 
      IP = L:match('IPv4 Address.*: (%d*.%d*.%d*.%d*).*Sub')
   end
   return IP
end

function server.Info()
   local Result = {}
   Result.IP = GetHost()
   Result.Label, Result.Port = GetServer()
   return Result
end