How to discover the IP address of the device from Lua
I was asked recently to retrieve the local IP address(es) of the device which is running a Storyboard application from Lua so that it can be displayed.
The topic has been touched on before and the most flexible approach for high-level OSes is to use the system calls approach described in this post : Performing system calls in Lua
The post has a simple application example which includes the intelligence to adapt the calls to the particular OS variant being used (via the target_os environment variable) although it might still need some adjustments as the system call input and output syntax can change over time...
The system call technique is very useful and can be applied to many different OS calls
Here is a snippet that can be used to determine the target platform environment:
local myenv = gre.env({ "target_os", "target_cpu" })
function get_ip()
local ip_addr = nil
if myenv["target_os"] == "qnx" then
ip_addr = get_ip_qnx()
elseif myenv["target_os"] == "linux" then
ip_addr = get_ip_linux()
elseif myenv["target_os"] == "macos" then
ip_addr = get_ip_macos()
elseif myenv["target_os"] == "windows" then
ip_addr = get_ip_win32()
else
print("Can't get IP, unsupported OS")
end
return(ip_addr)
end
And in the case of a Windows or Linux using the appropriate OS commands (ipconfig or ifconfig) with parsing logic example to retrieve the data of interest to return as a formatted Lua variable:
function get_ip_win32()
local ip_addr = nil
local f = assert( io.popen("ipconfig"))
for line in f:lines() do
if line:match("%sIPv4 Address") ~= nil then
ip_addr=line:match("%d+.%d+.%d+.%d+")
end
end
f:close()
return(ip_addr)
end
function get_ip_linux()
local ip_addr = nil
local f = assert( io.popen("ifconfig"))
for line in f:lines() do
if line:match("%sinet addr:") ~= nil then
ip_addr=line:match("%d+.%d+.%d+.%d+")
if ip_addr ~= "127.0.0.1" then
break
else
ip_addr = nil
end
end
end
f:close()
return(ip_addr)
end
Again this may need tweaking depending on platform but the approach is very useful.
Comments
Please sign in to leave a comment.