get IP Address in Lua

15,105

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.

Share:
15,105
christian Muller
Author by

christian Muller

Updated on June 04, 2022

Comments

  • christian Muller
    christian Muller almost 2 years

    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

    • michel-slm
      michel-slm over 12 years
      Not sure why socket.dns.toip(socket.dns.gethostname()) does not work; it works fine on my Linux installation of Lua. What exactly do you get when trying that on the device?
    • A. K.
      A. K. over 12 years
      to find your local ip you can use system commands 'ipconfig' on windows or 'ifconfig' on linux.
    • Doug Currie
      Doug Currie over 12 years
      Your WiFi does not have an IP address unless it has a network connection. Its IP address changes each time it connects to a new wireless network.
    • tomdemuyt
      tomdemuyt over 12 years
      With 'internet connection' do you mean 3G/Edge ?