get IP Address in Lua

christian Muller picture christian Muller · Aug 12, 2011 · Viewed 12.1k times · Source

i try to get the local IP from my device ( programming in Corona Lua )

till now I do with:

local myip = socket.dns.toip(socket.dns.gethostname()) 

but this only works on simulator

local client = socket.connect( "www.google.com", 80 )
local ip, port = client:getsockname() 

but this only works when I have a Internet Connection

How could i get my local IP just in my Wifi without Internet

thx chris

Answer

basicer picture basicer · Jan 23, 2012

The ip of the interface you are looking for can change based on what IP address you are trying to talk to. The code below uses google's IP to select an interface and return the IP address. It works me for me using LUA/luasocket but I haven't tried it in corona.

require "socket"

local s = socket.udp()
s:setpeername("74.125.115.104",80)
local ip, _ = s:getsockname()
print(ip)

EDIT:

You shouldn't need internet in this case because you're not actually connecting to anything or otherwise sending any packets. You will however need the interface in question to actually have an IP.