lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



> -----Original Message-----
> From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org] On
> Behalf Of Claudio Mussoni
> Sent: maandag 25 mei 2015 8:19
> To: lua-l@lists.lua.org
> Subject: Retrieve public IP
> 
> Hello to everyone,
> I need to get the public address from my router with LUA.
> 
> This is a PHP example:  $my_public_ip = $_SERVER['REMOTE_ADDR'];
> 
> I searched around but I' ve not found examples.
> Someone can help me out?
> Thank's a lot.
> Bye
> Claudio

This is what I came up with for the same issue;

local http = require("socket.http")
local json = require("dkjson")

-----------------------------------------
-- Fetches the external IP.
-- Uses http://ipinfo.io web service.
-- @return string IP address, or `nil + errormsg`
externalip = function()
  local resp,code,headers,status = http.request("http://ipinfo.io/json";)
  if code ~= 200 then return nil, "Failed fetching external IP; "..tostring(status) end
  local data, err = json.decode(resp)
  if not data then
    return nil, "Failed fetching external IP; "..tostring(err)
  end
  if data.ip then
    return data.ip
  else
    return nil, "Failed fetching external IP; no ip field was returned"
  end
end


relies on LuaSocket and the http://ipinfo.io service.

Thijs