How can I identify the ISP associated with an IP address in Lua?

To determine the ISP of an IP address using IP2Location.io in Lua, you can use the IP2Location.io API to retrieve geolocation and related data.

  1. We'll assume that you have already installed Lua & LuaRocks and we won't cover that here. You will also need a paid subscription to the Starter plan or higher. Subscribe now!
  2. In the command line, run the commands below to install the dependencies using LuaRocks if you don't have them installed.
    Bash
    
    luarocks install json-lua
    luarocks install luasocket
    			
  3. Save the below code into a file called test.lua on your computer.
    Lua
    
    local http = require("socket.http")
    local ltn12 = require("ltn12")
    local json = require("JSON")
    
    local t = {}
    local ip = "8.8.8.8"
    local key = "YOUR_API_KEY"
    
    local full_url = "https://api.ip2location.io/?format=json&key=" .. key .. "&ip=" .. ip
    
    local status, code, headers = http.request({
        method = "GET",
        url = full_url,
        sink = ltn12.sink.table(t),
      })
    local jsonstr = table.concat(t)
    
    if code == 200 then
      local result = json:decode(jsonstr)
      if result.isp ~= nil then
        print("The ISP for IP " .. ip .. " is " .. result.isp .. ".")
      else
        error("ERROR: The isp field requires a paid subscription to the Starter plan or higher.")
      end
    elseif code == 400 or code == 401 then
      if jsonstr:find("error_message") then
        local result = json:decode(jsonstr)
        error("ERROR: " .. result.error.error_message)
      else
        error(jsonstr)
      end
    else
      error("ERROR: Unable to call API.")
    end
    			
  4. In the command line, run the below command.
    Bash
    
    lua test.lua
    			

This script will output the ISP of specified IP address. Make sure to replace 8.8.8.8 with the IP address you want and replace YOUR_API_KEY to your own API key.

Other Languages

Unlock Location Insights For Free

Empower your applications with accurate IP geolocation information now.

Try It for Free