Back to Ntopng

ntopng Lua API Reference (`ntop.*` bindings)

doc/README.lua_ntop_api.md

6.645.4 KB
Original Source

ntopng Lua API Reference (ntop.* bindings)

This document describes all C→Lua bindings exposed as ntop.* functions via src/LuaEngineNtop.cpp. It is intended both for human developers writing Lua scripts and as a machine-readable reference for AI-assisted code generation (e.g. Claude Code in this repository).


Table of Contents

  1. How the Lua API works
  2. REST API development guide
  3. System & Information
  4. File System
  5. Redis / Cache
  6. Preferences
  7. User Management & Authentication
  8. MFA / TOTP
  9. Network & IP Utilities
  10. Address Resolution
  11. HTTP Client
  12. Logging
  13. Historical Statistics (SQLite)
  14. RRD
  15. Alerts
  16. Recipient Queues
  17. nDPI / Protocol Classification
  18. SNMP
  19. Ping
  20. Traffic Recording & Extraction
  21. IPS / nEdge
  22. ZMQ
  23. Time & Ticks
  24. UDP / TCP Send
  25. ASN & Geolocation
  26. Bitmap Utilities
  27. Score / Severity
  28. Edition / Platform Checks
  29. Privilege Management
  30. Custom Categories & nDPI Reload
  31. Flow / Host Checks & Risks
  32. In-Memory Lua Cache
  33. Miscellaneous

1. How the Lua API works

C→Lua registration

Every Lua function registered in _ntop_reg[] (bottom of src/LuaEngineNtop.cpp) follows this pattern:

c
// 1. Implement a static C function
static int ntop_my_function(lua_State* vm) {
    // read args
    ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING);
    const char* arg = lua_tostring(vm, 1);
    // do work, push return value
    lua_pushstring(vm, result);
    return CONST_LUA_OK;  // or CONST_LUA_ERROR
}

// 2. Register it
{ "myFunction", ntop_my_function },   // called as ntop.myFunction(...)

Script request flow

HTTP request → HTTPserver.cpp → Lua VM → scripts/lua/<path>.lua
                                          ├── _GET["param"]        (GET params)
                                          ├── _POST["param"]       (POST params)
                                          ├── _SESSION["user"]     (logged-in username)
                                          ├── _SESSION["group"]    (user role)
                                          └── ntop.*()             (C bindings)

Standard boilerplate (all Lua scripts)

lua
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path

require "lua_utils"        -- helper utilities
local json = require("dkjson")
local rest_utils = require("rest_utils")  -- for REST endpoints

2. REST API development guide

File location

REST endpoints live at:

scripts/lua/rest/v2/<method>/<resource>/<sub-resource>.lua
HTTP methodDirectory
GETget/
POSTadd/, create/, set/, edit/
DELETEdelete/
PUT/PATCHedit/

The URL to call an endpoint is:

http(s)://<host>:3000/lua/rest/v2/<method>/<resource>/<sub>.lua

Minimal REST endpoint template

lua
-- (C) 2013-26 - ntop.org

local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path

local rest_utils = require("rest_utils")
require "lua_utils"
local json = require("dkjson")

-- ── Read parameters ──────────────────────────────────────────────────────────
local ifid   = _GET["ifid"]
local param1 = _GET["param1"]

-- ── Validate ─────────────────────────────────────────────────────────────────
if isEmptyString(ifid) then
   rest_utils.answer(rest_utils.consts.err.invalid_interface)
   return
end

if isEmptyString(param1) then
   rest_utils.answer(rest_utils.consts.err.invalid_args)
   return
end

-- ── Authorization ─────────────────────────────────────────────────────────────
if not isAdministrator() then
   rest_utils.answer(rest_utils.consts.err.not_granted)
   return
end

-- ── Work ─────────────────────────────────────────────────────────────────────
interface.select(ifid)

local result = {}
-- populate result ...

-- ── Return JSON ───────────────────────────────────────────────────────────────
rest_utils.answer(rest_utils.consts.success.ok, result)

rest_utils.answer(rc [, data])

rc must be one of the constants in rest_utils.consts:

Success codes

ConstantHTTPrcMeaning
success.ok2000Generic success

Error codes

ConstantHTTPrcMeaning
err.not_found404-1Resource not found
err.invalid_interface400-2Bad/missing interface id
err.not_granted401-3Insufficient privileges
err.invalid_host400-4Bad host
err.invalid_args400-5Missing/bad arguments
err.internal_error500-6Server error
err.bad_format400-7Malformed data
err.bad_content400-8Bad content

Common patterns

Selecting an interface

lua
local ifid = _GET["ifid"]
interface.select(ifid)
-- now interface.* calls operate on that interface

Reading Redis data

lua
local value = ntop.getCache("ntopng.prefs.my_key")
ntop.setCache("ntopng.prefs.my_key", "new_value", 3600)  -- optional TTL

Reading/writing hash maps

lua
ntop.setHashCache("ntopng.user.admin", "language", "en")
local lang = ntop.getHashCache("ntopng.user.admin", "language")

JSON encode/decode

lua
local json = require("dkjson")
local encoded = json.encode({ key = "value" })
local decoded = json.decode(encoded)

Admin-only guard

lua
if not isAdministrator() then
   rest_utils.answer(rest_utils.consts.err.not_granted)
   return
end

POST body (JSON)

lua
local body = _POST["JSON"]          -- raw JSON string
local data = json.decode(body or "")
local field = data and data["field"]

3. System & Information

Lua callReturnsDescription
ntop.getDirs()tableAll ntopng directory paths: installdir, scriptdir, httpdocsdir, workingdir, bindir, callbacksdir, pcapdir, dbarchivedir, etcdir, sharedir
ntop.getInfo([verbose])tableProduct info, version, OS, license, uptime, port numbers. Pass false for a smaller payload.
ntop.getUptime()integerUptime in seconds since last restart
ntop.systemHostStat()tableCPU load, memory usage, alert queue drops/writes
ntop.threadsInfo()tableAll running ntopng threads
ntop.refreshCPULoad()number|nilTrigger CPU load refresh; returns current value
ntop.checkLicense()integerRun license validation (returns 1)
ntop.getSystemAlertsStats()tableAlert statistics (drops, writes)
ntop.getCookieAttributes()stringCookie security attributes string (e.g. SameSite=Strict; Secure)
ntop.getAllPaths(path, pattern)tableRecursively find all files matching pattern under path
ntop.getStartupEpoch()integerntopng start time as Unix epoch
ntop.getStaticFileEpoch()integerEpoch for static-file cache busting
ntop.getHttpPrefix()stringHTTP path prefix (e.g. empty string or subpath)
ntop.httpPurifyParam(s)stringSanitize a string for safe use in URLs/HTML
ntop.isShuttingDown()booleanTrue if ntopng is in shutdown sequence
ntop.limitResourcesUsage()nilThrottle CPU usage of current thread
ntop.getCurrentScriptsDir()stringPath of currently executing scripts directory
ntop.getInstanceName()stringConfigured instance name
ntop.resetStats()nilReset per-interface statistics
ntop.getDropPoolInfo()tableDrop pool statistics

Example — get version:

lua
local info = ntop.getInfo()
print(info["version"])   -- e.g. "6.1.230101"

Example — get dirs:

lua
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path

4. File System

Lua callReturnsDescription
ntop.isdir(path)booleanTrue if path is a directory
ntop.mkdir(path)nilCreate directory tree (like mkdir -p)
ntop.notEmptyFile(path)booleanTrue if file exists and has content
ntop.exists(path)booleanTrue if file or directory exists
ntop.fileLastChange(path)integerModification time (Unix epoch), -1 if missing
ntop.readdir(path)tableList of filenames in directory
ntop.rmdir(path)booleanRemove directory recursively
ntop.unlink(path)booleanDelete a file
ntop.dumpFile(path)nilRead text file and write to HTTP response
ntop.dumpBinaryFile(path)nilRead binary file and write to HTTP response
ntop.listReports()tableList available report files
ntop.setDefaultFilePermissions(path)nilApply default Unix permissions to file

5. Redis / Cache

ntopng uses Redis for persistent key-value storage. All user preferences, session tokens, and many runtime values live here.

Key conventions

PrefixPurpose
ntopng.user.<username>.<field>Per-user settings
ntopng.prefs.<key>System preferences
sessions.<session_id>Active sessions (value: user|group|csrf|localuser)

String operations

Lua callParamsReturnsDescription
ntop.getCache(key)stringstring|nilGet key value
ntop.setCache(key, val [,ttl])string, string, int?nilSet key, optional TTL in seconds
ntop.setnxCache(key, val)string, stringbooleanSet only if key absent
ntop.delCache(key)stringnilDelete key
ntop.renameCache(old, new)string, stringnilRename key
ntop.incrCache(key [,n])string, int?integerAtomic increment (default +1)
ntop.flushCache()booleanDANGER: flush all Redis data (admin only)
ntop.getKeysCache(pattern)stringtableKeys matching glob pattern
ntop.getCacheStatus()tableRedis connection info and statistics
ntop.getCacheStats()tableRedis usage statistics
ntop.hasDumpCache(key)stringbooleanTrue if key has a binary dump
ntop.dumpCache(key)stringstring|nilBinary dump of key
ntop.restoreCache(key, dump)string, stringbooleanRestore key from binary dump

Hash operations

Lua callParamsReturnsDescription
ntop.getHashCache(key, field)string, stringstring|nilGet hash field
ntop.setHashCache(key, field, val)string, string, stringnilSet hash field
ntop.delHashCache(key, field)string, stringnilDelete hash field
ntop.getHashKeysCache(key)stringtableAll field names in hash
ntop.getHashAllCache(key)stringtableAll {field=value} pairs

List operations

Lua callParamsReturnsDescription
ntop.lpushCache(key, val)string, stringnilPush to list head
ntop.rpushCache(key, val)string, stringnilPush to list tail
ntop.lpopCache(key)stringstring|nilPop from list head
ntop.rpopCache(key)stringstring|nilPop from list tail
ntop.lremCache(key, count, val)string, int, stringnilRemove matching elements
ntop.ltrimCache(key, start, stop)string, int, intnilTrim list to range
ntop.lrangeCache(key, start, stop)string, int, inttableGet range of elements
ntop.llenCache(key)stringintegerList length
ntop.listIndexCache(key, idx)string, intstring|nilElement at index

Set operations

Lua callParamsReturnsDescription
ntop.setMembersCache(key, member)string, stringnilAdd member to set
ntop.delMembersCache(key, member)string, stringnilRemove member from set
ntop.getMembersCache(key)stringtableAll set members

Examples:

lua
-- Store per-user setting
ntop.setHashCache("ntopng.user.admin", "language", "it")

-- Read it back
local lang = ntop.getHashCache("ntopng.user.admin", "language")

-- Store JSON configuration
local json = require("dkjson")
ntop.setCache("ntopng.prefs.my_config", json.encode({enabled=true, threshold=100}))
local cfg = json.decode(ntop.getCache("ntopng.prefs.my_config") or "{}")

6. Preferences

Lua callParamsReturnsDescription
ntop.setPref(key, val)string, stringnilWrite preference to Redis (ntopng.prefs.<key>)
ntop.getPref(key)stringstring|nilRead preference (alias for getCache)
ntop.getPrefs()tableAll preferences as a table
ntop.reloadPreferences([set_defaults])bool?nilReload preferences from Redis
lua
-- Save a preference
ntop.setPref("ntopng.prefs.my_feature_enabled", "1")

-- Read it back
local enabled = (ntop.getPref("ntopng.prefs.my_feature_enabled") == "1")

7. User Management & Authentication

These functions are admin-only unless otherwise noted.

Querying users

Lua callReturnsDescription
ntop.getUsers()tableAll users with their attributes
ntop.getNologinUser()stringThe special no-login username constant
ntop.isAdministrator()booleanTrue if current request is from an admin
ntop.isPcapDownloadAllowed()booleanTrue if current user may download PCAPs
ntop.getAllowedNetworks()tableNetworks visible to current user
ntop.getAllowedHostPools()tableHost pools visible to current user
ntop.isLoginDisabled()booleanTrue if login is globally disabled
ntop.isLoginBlacklisted(username)booleanTrue if username is brute-force blocked
ntop.isGuiAccessRestricted()booleanTrue if GUI access is IP-restricted
ntop.getUserObservationPointId(username)integerObservation point assigned to user

Creating / modifying users

Lua callParamsReturnsDescription
ntop.addUser(username, full_name, password, role, allowed_nets, allowed_iface [, host_pool, lang, pcap, history, alerts, pools])booleanCreate new user
ntop.deleteUser(username)stringbooleanDelete user
ntop.resetUserPassword(who, username, old_pw, new_pw)booleanChange password
ntop.changeUserRole(username, role)string, stringbooleanChange role (administrator/unprivileged/captivePortal)
ntop.changeAllowedNets(username, nets)string, stringbooleanUpdate allowed networks (comma-separated CIDR)
ntop.changeAllowedIfname(username, ifname)string, stringbooleanUpdate allowed interface
ntop.changeUserHostPool(username, pool_id)string, stringbooleanSet captive portal host pool
ntop.changeAllowedHostPools(username, pools)string, stringbooleanSet viewable host pools
ntop.changeUserFullName(username, name)string, stringbooleanUpdate display name
ntop.changeUserLanguage(username, lang)string, stringbooleanUpdate UI language
ntop.changePcapDownloadPermission(username, allow)string, boolbooleanGrant/revoke PCAP download
ntop.changeHistoricalFlowPermission(username, allow)string, boolbooleanGrant/revoke historical flows
ntop.changeAlertsPermission(username, allow)string, boolbooleanGrant/revoke alerts access

Sessions & tokens

Lua callParamsReturnsDescription
ntop.createUserSession(username [, duration])string, int?stringCreate session, returns session id
ntop.createUserAPIToken(username)stringstring|nilGenerate new API token
ntop.getUserAPIToken(username)stringstring|nilRead existing API token

Example — create user via REST endpoint:

lua
local ok = ntop.addUser(
  "analyst",                  -- username
  "Jane Analyst",             -- full name
  "s3cr3t",                   -- initial password
  "unprivileged",             -- role
  "192.168.1.0/24",          -- allowed networks
  "eth0",                     -- allowed interface
  nil,                        -- host pool (nil = all)
  "en",                       -- language
  false,                      -- pcap download
  true,                       -- historical flows
  true                        -- alerts
)

8. MFA / TOTP

Lua callParamsReturnsDescription
ntop.generateTOTPSecret()stringGenerate new base32 TOTP secret
ntop.setUserTOTPSecret(username, secret)string, stringbooleanStore secret for user
ntop.getUserTOTPSecret(username)stringstring|nilRead secret (admin only)
ntop.isTOTPEnabled(username)stringbooleanCheck if TOTP is on
ntop.setUserTOTPEnabled(username, enabled)string, boolbooleanEnable/disable TOTP
ntop.validateTOTP(username, code)string, stringbooleanValidate 6-digit code
ntop.getTOTPProvisioningUri(username)stringstring|nilQR-code URI for authenticator app setup

9. Network & IP Utilities

Lua callParamsReturnsDescription
ntop.ipToNumber(ip)stringintegerIPv4 string → 32-bit number
ntop.inet_ntoa(n)integer|stringstring32-bit number → IPv4 string
ntop.networkPrefix(ip, bits)string, intstringNetwork address from IP + prefix length
ntop.ipCmp(ip1, ip2)string, stringintegerCompare two IPs (-1/0/1)
ntop.isIPv6(ip)stringbooleanTrue if address is IPv6
ntop.isLocalAddress(ip)stringbooleanTrue if in a configured local network
ntop.isLocalInterfaceAddress(ip)stringbooleanTrue if IP belongs to a local NIC
ntop.isAllowedInterface(ifname)stringbooleanTrue if current user may see this interface
ntop.isAllowedNetwork(network)stringbooleanTrue if current user may see this network
ntop.addLocalNetwork(cidr)stringnilAdd CIDR to local networks list
ntop.getNetworks()tableAll configured local networks
ntop.getNetworkNameById(id)integerstringNetwork name for index
ntop.getNetworkIdByName(name)stringintegerIndex for network name
ntop.getAddressNetwork(ip)stringtableNetwork info for an IP
ntop.getLocalNetworkAlias(cidr)stringstring|nilAlias for a local network
ntop.getLocalNetworkID(cidr)stringintegerID for local network CIDR
ntop.setResolvedAddress(ip, hostname)string, stringnilCache DNS reverse mapping
ntop.checkNetworkPolicy(ip)stringtableNetwork policy for an IP

10. Address Resolution

Lua callParamsReturnsDescription
ntop.resolveName(ip)stringnilTrigger async DNS resolution (see ntop_utils.resolveAddress())
ntop.getResolvedName(ip)stringstring|nilRetrieve cached reverse DNS result
ntop.resolveHost(hostname)stringstring|nilResolve hostname → IP

Note: use the Lua wrappers resolveAddress() / getResolvedAddress() from lua_utils instead of calling these directly.


11. HTTP Client

These functions let Lua scripts make outbound HTTP requests.

Lua callParamsReturnsDescription
ntop.httpGet(url [, user, pass, timeout, return_content, no_verify_cert, use_compression, follow_redirects])string|tableGET request; returns body or nil
ntop.httpPost(url, body [, user, pass, timeout, return_content, content_type])stringPOST request
ntop.httpFetch(params_table)tabletableFull-featured HTTP fetch with all options
ntop.httpGetAuthToken(url, token [, timeout, return_content, no_verify_cert])stringGET with Bearer token
ntop.httpPostAuthToken(url, token, body [, timeout, content_type])stringPOST with Bearer token
ntop.httpPutAuthToken(url, token, body [, timeout])stringPUT with Bearer token
ntop.httpPatchAuthToken(url, token, body [, timeout])stringPATCH with Bearer token
ntop.postHTTPJsonData(url, body)string, stringbooleanPOST JSON body
ntop.postHTTPTextFile(url, file_path)string, stringbooleanPOST text file content
ntop.httpRedirect(url)stringnilIssue HTTP 302 redirect (from page script)
ntop.getRandomCSRFValue()stringCSRF token for form/AJAX protection

Example — calling an external REST API:

lua
local json = require("dkjson")
local body = ntop.httpGet("https://api.example.com/data", nil, nil, 5, true)
if body then
   local data = json.decode(body)
end

12. Logging

Lua callParamsReturnsDescription
ntop.traceEvent(level, msg)integer, stringnilLog a message at given level
ntop.verboseTrace(msg)stringnilLog at verbose level only if verbose mode on
ntop.setLoggingLevel(level)stringnilSet global log level ("debug", "normal", "warning", etc.)
ntop.syslog(level, msg)integer, stringnilWrite to syslog (Unix only)

Trace levels (defined in ntop_defines.h):

lua
TRACE_ERROR   = 0
TRACE_WARNING = 1
TRACE_NORMAL  = 2
TRACE_INFO    = 3
TRACE_DEBUG   = 4
lua
ntop.traceEvent(TRACE_WARNING, "unexpected value: " .. tostring(v))

13. Historical Statistics (SQLite)

Used by housekeeping scripts to store per-interface time-series data.

Lua callParamsReturnsDescription
ntop.insertMinuteSampling(ifid, data)int, stringnilInsert minute-granularity sample
ntop.insertHourSampling(ifid, data)int, stringnilInsert hour-granularity sample
ntop.insertDaySampling(ifid, data)int, stringnilInsert day-granularity sample
ntop.getMinuteSampling(ifid, epoch)int, intstring|nilGet minute sample for epoch
ntop.getMinuteSamplingsFromEpoch(ifid, epoch)int, inttableAll minute samples from epoch
ntop.getHourSamplingsFromEpoch(ifid, epoch)int, inttableAll hour samples from epoch
ntop.getDaySamplingsFromEpoch(ifid, epoch)int, inttableAll day samples from epoch
ntop.getMinuteSamplingsInterval(ifid, from, to)int, int, inttableMinute samples in epoch range
ntop.deleteMinuteStatsOlderThan(ifid, days)int, intnilPurge old minute data
ntop.deleteHourStatsOlderThan(ifid, days)int, intnilPurge old hour data
ntop.deleteDayStatsOlderThan(ifid, days)int, intnilPurge old day data

14. RRD

Lua callParamsReturnsDescription
ntop.rrd_create(path, step, start, ...)nilCreate RRD file
ntop.rrd_update(path, timestamp, ...)nilUpdate RRD with new values
ntop.rrd_fetch(path, cf, start, stop [, step])tableFetch consolidated data
ntop.rrd_fetch_columns(path, cf, start, stop [, step])tableFetch data column-oriented
ntop.rrd_lastupdate(path)stringinteger|nilLast update timestamp
ntop.rrd_tune(path, ...)nilModify RRD parameters
ntop.rrd_inc_num_drops(path)stringnilIncrement drop counter in RRD
ntop.deleteOldRRDs()nilRemove stale RRD files

15. Alerts

Alert store queries (ClickHouse / SQLite)

Lua callParamsReturnsDescription
ntop.alert_store_query(query [, ifid, limit_rows])string, int?, bool?nilExecute raw alert DB query, streaming JSON result to response
ntop.popInternalAlerts()tableDequeue internal alert events

Score / severity mapping

See section 27. Score / Severity.


16. Recipient Queues

Recipient queues are used to distribute alert notifications to configured notification channels (e.g. Slack, email, syslog).

Lua callParamsReturnsDescription
ntop.recipient_register(id)stringnilRegister a recipient channel
ntop.recipient_delete(id)stringnilUnregister a recipient channel
ntop.recipient_enqueue(id, notification)string, stringnilPush notification JSON to queue
ntop.recipient_dequeue(id)stringstring|nilPop next notification from queue
ntop.recipient_stats()tableQueue length and throughput per recipient
ntop.recipient_inc_stats(id, stat)string, stringnilIncrement named counter
ntop.recipient_last_use(id)stringintegerEpoch of last dequeue

17. nDPI / Protocol Classification

Lua callParamsReturnsDescription
ntop.getnDPIProtoCategory(proto_id)integerintegerGet category for nDPI protocol
ntop.setnDPIProtoCategory(proto_id, cat)integer, integernilOverride protocol category
ntop.isCustomApplication(proto_id)integerbooleanTrue if protocol is user-defined
ntop.matchCustomCategory(hostname)stringinteger|nilMatch hostname against custom categories
ntop.initnDPIReload()nilBegin nDPI category reload (housekeeping only)
ntop.finalizenDPIReload()nilCommit nDPI category reload
ntop.loadCustomCategoryIp(cat, ip)integer, stringnilAssociate IP with custom category
ntop.loadCustomCategoryHost(cat, host)integer, stringnilAssociate hostname with custom category
ntop.loadCustomCategoryFile(cat, path)integer, stringnilLoad IPs/hosts from file into category
ntop.setDomainMask(domain, mask)string, integernilApply mask to domain traffic
ntop.addTrustedIssuerDN(dn)stringnilTrust TLS certificate issuer DN

18. SNMP

Configuration

Lua callParamsReturnsDescription
ntop.snmpv3available()booleanTrue if SNMPv3 library present
ntop.snmpsetavailable()booleanTrue if SNMP SET supported
ntop.snmpgetbulkavailable()booleanTrue if SNMP GETBULK supported
ntop.snmpMaxNumEngines()integerMax concurrent SNMP engines
ntop.snmpSetBulkMaxNumRepetitions(n)integernilSet BULK repetitions
ntop.snmpSetFatMibPollingMode(enabled)boolnilEnable full MIB polling
ntop.snmpToggleTrapCollection(enabled)boolnilEnable/disable trap collection
ntop.snmpSetInterfaceRole(ip_addr, interface_idx, role_id)-nilSet the SNMP interface role in memory that is then activated using ntop.snmpSetInterfaceRole()
ntop.activateSnmpInterfaceRoles()-nilActivate the interface roles set with ntop.snmpSetInterfaceRole()

Synchronous (blocking)

Lua callParamsReturnsDescription
ntop.snmpget(host, community, oid, version)tableSNMP GET (blocks)
ntop.snmpgetnext(host, community, oid, version)tableSNMP GETNEXT (blocks)
ntop.snmpgetnextbulk(host, community, oid, version)tableSNMP GETBULK (blocks)
ntop.snmpset(host, community, oid, type, value, version)booleanSNMP SET (blocks)

Asynchronous

Lua callParamsReturnsDescription
ntop.snmpallocasnyncengine()integerAllocate async engine, returns handle
ntop.snmpfreeasnycengine(handle)integernilFree async engine
ntop.snmpgetasync(handle, host, community, oid, version)nilQueue async GET
ntop.snmpgetnextasync(handle, host, community, oid, version)nilQueue async GETNEXT
ntop.snmpgetnextbulkasync(handle, …)nilQueue async GETBULK
ntop.snmpreadasyncrsp(handle)integertable|nilRead pending async responses

Batch

Lua callParamsReturnsDescription
ntop.snmpGetBatch(params)tablenilSubmit batch SNMP GETs (v1/v2c/v3)
ntop.snmpReadResponses()tableCollect batch responses

19. Ping

Lua callParamsReturnsDescription
ntop.isPingAvailable()booleanTrue if raw socket ping works
ntop.isPingIfaceAvailable(ifname)stringbooleanTrue if ping on interface works
ntop.pingHost(host, is_v6, iface)string, bool, stringnilSend ICMP ping
ntop.collectPingResults()tableCollect RTT results from sent pings
ntop.getPingIfNames()tableList interfaces usable for ping

20. Traffic Recording & Extraction

Lua callParamsReturnsDescription
ntop.runExtraction(id, ifid, from, to, filter [,max_bytes, timeline])nilStart PCAP extraction job (admin only)
ntop.stopExtraction(id)integernilStop extraction job
ntop.isExtractionRunning()booleanTrue if any extraction active
ntop.getExtractionStatus()nil(reserved)
ntop.runLiveExtraction(ifid, from, to, bpf [, timeline])booleanStart live PCAP stream

21. IPS / nEdge

These are only available in non-nEdge builds (#ifndef HAVE_NEDGE).

Lua callDescription
ntop.broadcastIPSMessage(msg)Broadcast message to IPS subsystem
ntop.timeToRefreshIPSRules()Returns true if IPS rules need refreshing
ntop.askToRefreshIPSRules()Request IPS rule refresh
ntop.checkSubInterfaceSyntax(str)Validate sub-interface syntax (Pro)
ntop.checkFilterSyntax(str)Validate BPF filter syntax (Pro)
ntop.reloadProfiles()Reload traffic profiles (Pro)

nEdge-only:

Lua callDescription
ntop.setHTTPBindAddr(addr)Set HTTP listen address
ntop.setHTTPSBindAddr(addr)Set HTTPS listen address
ntop.setRoutingMode(enabled)Enable routing mode
ntop.isRoutingMode()True if routing mode
ntop.addLanInterface(ifname)Register LAN interface
ntop.addWanInterface(ifname)Register WAN interface
ntop.refreshDeviceProtocolsPoliciesConf()Refresh device-protocol policy config

22. ZMQ

Available only in non-nEdge builds with HAVE_ZMQ.

Lua callParamsReturnsDescription
ntop.zmq_connect(endpoint, topic)string, stringnilConnect to ZMQ publisher
ntop.zmq_disconnect()nilDisconnect
ntop.zmq_receive()string|errorReceive next ZMQ message

23. Time & Ticks

Lua callReturnsDescription
ntop.gettimemsec()numberCurrent time in milliseconds (float)
ntop.getticks()integerCPU tick counter
ntop.gettickspersec()integerCPU ticks per second
ntop.tzset()nilRefresh timezone information
ntop.roundTime(epoch, secs [, timezone])integerRound epoch down to multiple of secs
lua
local now_ms = ntop.gettimemsec()
local rounded = ntop.roundTime(os.time(), 60)  -- round to last minute

24. UDP / TCP Send

Lua callParamsReturnsDescription
ntop.send_udp_data(host, port, data)string, int, stringnilSend UDP datagram
ntop.send_tcp_data(host, port, data)string, int, stringnilSend TCP data (persistent connection)
ntop.tcpProbe(host, port [, timeout])string, int, int?booleanTest TCP reachability

25. ASN & Geolocation

Lua callParamsReturnsDescription
ntop.hasGeoIP()booleanTrue if MaxMind GeoIP databases loaded
ntop.getASName(ip)stringstring|nilASN name for an IP
ntop.getASNameFromASN(asn)integerstring|nilASN name from ASN number
ntop.getHostGeolocation(ip)stringtableCountry, city, lat/lon for IP
ntop.getMacManufacturer(mac)stringstring|nilVendor name from MAC OUI
ntop.getHostInformation(ip)stringtableCombined host info table

26. Bitmap Utilities

Lua callParamsReturnsDescription
ntop.bitmapIsSet(bitmap, val)integer, integerbooleanTest bit
ntop.bitmapSet(bitmap, val)integer, integerintegerSet bit, return new bitmap
ntop.bitmapClear(bitmap, val)integer, integerintegerClear bit, return new bitmap
lua
local bm = 0
bm = ntop.bitmapSet(bm, 3)        -- set bit 3
if ntop.bitmapIsSet(bm, 3) then   -- test bit 3
   bm = ntop.bitmapClear(bm, 3)   -- clear bit 3
end

27. Score / Severity

Lua callParamsReturnsDescription
ntop.mapScoreToSeverity(score)integerintegerConvert numeric score → alert severity enum
ntop.mapSeverityToScore(severity)integerintegerConvert severity enum → numeric score
ntop.getFlowAlertScore(alert_id)integerintegerDefault score for a flow alert type
ntop.getFlowAlertRisk(alert_id)integerintegerRisk identifier for a flow alert

28. Edition / Platform Checks

Edition

Lua callReturnsDescription
ntop.isForcedCommunity()booleanForced Community mode
ntop.isPro()booleanPro or better
ntop.isEnterprise()booleanEnterprise M or better (alias isEnterpriseM)
ntop.isEnterpriseM()booleanEnterprise M
ntop.isEnterpriseL()booleanEnterprise L
ntop.isEnterpriseXL()booleanEnterprise XL
ntop.isEnterpriseXXL()booleanEnterprise XXL
ntop.isnEdge()booleannEdge Pro
ntop.isnEdgeEnterprise()booleannEdge Enterprise
ntop.isPackage()booleanRunning from a package install
ntop.isAppliance()booleanRunning on hardware appliance
ntop.isIoTBridge()booleanIoT Bridge mode

Platform

Lua callReturnsDescription
ntop.isWindows()booleanWindows
ntop.isFreeBSD()booleanFreeBSD
ntop.isLinux()booleanLinux

Runtime features

Lua callReturnsDescription
ntop.hasGeoIP()booleanGeoIP databases present
ntop.hasRadiusSupport()booleanRADIUS auth compiled in
ntop.hasLdapSupport()booleanLDAP auth compiled in
ntop.isPingAvailable()booleanICMP ping usable
ntop.isClickHouseEnabled()booleanClickHouse backend active
ntop.hasSpeedtestSupport()booleanSpeedtest compiled in
ntop.isNProbeIPSConfigured()booleannProbe IPS configured
ntop.isFlowDedupEnabled()booleanFlow deduplication active
ntop.getLicenseLimits()tableLicense capacity limits

29. Privilege Management

On Unix, ntopng may need elevated privileges for some operations (writing raw sockets, packet capture) while running as a non-root user after privilege drop.

Lua callReturnsDescription
ntop.gainWriteCapabilities()booleanTemporarily re-acquire write capabilities
ntop.dropWriteCapabilities()booleanDrop back to low-privilege mode

30. Custom Categories & nDPI Reload

Called from scripts/lua/housekeeping.lua to hot-reload nDPI configuration.

lua
-- Typical usage in housekeeping
ntop.initnDPIReload()
ntop.loadCustomCategoryIp(cat_id, "192.168.1.0/24")
ntop.loadCustomCategoryHost(cat_id, "ads.example.com")
ntop.loadCustomCategoryFile(cat_id, "/etc/ntopng/custom_hosts.txt")
ntop.setDomainMask("example.com", 0x1)
ntop.addTrustedIssuerDN("CN=MyCA,O=MyOrg")
ntop.finalizenDPIReload()

31. Flow / Host Checks & Risks

Check management

Lua callParamsReturnsDescription
ntop.reloadFlowChecks()nilHot-reload flow check scripts
ntop.reloadHostChecks()nilHot-reload host check scripts
ntop.reloadAlertExclusions()nilHot-reload alert exclusion rules
ntop.getFlowChecksStats()tableFlow check execution statistics
ntop.getFlowCheckInfo(check_id)integertableMetadata for a flow check
ntop.getHostCheckInfo(check_id)integertableMetadata for a host check

Risk API

Lua callParamsReturnsDescription
ntop.getRiskStr(risk_id)integerstringHuman-readable risk name
ntop.getRiskList()tableAll known risk ids and names
ntop.getFlowRiskAlerts()tableMap of risk id → alert type
ntop.shouldResolveHost(ip)stringbooleanTrue if host resolution is warranted

IEC 104 / Modbus (OT security)

Lua callParamsDescription
ntop.setIEC104AllowedTypeIDs(ids_table)tableWhitelist IEC 104 type IDs
ntop.setModbusAllowedFunctionCodes(codes_table)tableWhitelist Modbus function codes (Pro)
ntop.readModbusDeviceInfo(host, port)string, intQuery Modbus device identification
ntop.readEthernetIPDeviceInfo(host, port)string, intQuery EtherNet/IP device identification

32. In-Memory Lua Cache

A fast in-process cache shared across Lua VMs (does not survive restarts).

Lua callParamsReturnsDescription
ntop.getLuaCache(key)stringany|nilGet value from in-process cache
ntop.setLuaCache(key, value [, ttl])string, any, int?nilStore value with optional TTL
ntop.dumpLuaCache()tableDump all cache entries (debug)
lua
-- Cache expensive computation for 60 seconds
local cached = ntop.getLuaCache("my_expensive_result")
if not cached then
   cached = computeExpensiveResult()
   ntop.setLuaCache("my_expensive_result", cached, 60)
end

33. Miscellaneous

Lua callParamsReturnsDescription
ntop.msleep(ms)integernilSleep N milliseconds
ntop.md5(data)stringstringMD5 hex digest
ntop.getservbyport(port, proto)int, stringstringService name for port number
ntop.getTLSVersionName(id)integerstringTLS version string (e.g. "TLSv1.3")
ntop.getMac64(mac)stringstringExpand 48-bit MAC to 64-bit EUI-64
ntop.decodeMac64(mac64)stringstringDecode EUI-64 back to MAC
ntop.isDeadlineApproaching()booleanTrue if periodic script near deadline
ntop.getDeadline()integerDeadline epoch for current periodic script
ntop.speedtest()tableRun speedtest and return results (Pro)
ntop.getBlacklistStats()tableIP blacklist hit statistics
ntop.resetBlacklistStats()nilReset blacklist counters
ntop.isOffline()booleanTrue if ntopng is in offline mode
ntop.isForcedOffline()booleanTrue if offline forced via CLI
ntop.setOffline()nilEnter offline mode
ntop.setOnline()nilLeave offline mode
ntop.serviceRestart()nilRestart ntopng service
ntop.shutdown()nilShutdown ntopng (nEdge/Appliance)
ntop.poolsLock()nilAcquire pools write lock
ntop.poolsUnlock()nilRelease pools write lock
ntop.enableAssetsLog()nilEnable asset logging
ntop.assetsEnabled()booleanTrue if asset discovery enabled
ntop.overrideInterface(ifname)stringnilOverride current interface (Appliance)
ntop.registerRuntimeInterface(params)tablenilRegister PCAP or DB runtime interface
ntop.reloadHostPools()nilReload host pool configuration
ntop.reloadDeviceProtocols()nilReload device-protocol rules
ntop.reloadServersConfiguration()nilReload server configurations
ntop.reloadASNConfiguration()nilReload custom ASN configuration
ntop.reloadNetworksPolicyConfiguration()nilReload networks policy (Pro)
ntop.execCmd(cmd)stringstring|nilExecute shell command, return stdout
ntop.execCmdAsync(cmd)stringintegerStart async shell command, return handle
ntop.readResultCmdAsync(handle)integerstring|nilRead output of async command
ntop.logRadius(info)tablenilLog RADIUS authentication event
ntop.updateRadiusLoginInfo(info)tablenilUpdate RADIUS login state
ntop.addBin(name, val, weight)string, number, numbernilAdd data point for similarity binning
ntop.findSimilarities(name)stringtableFind similar bins by Euclidean distance
ntop.publish(topic, msg)string, stringnilPublish to message broker (Pro)
ntop.rpcCall(topic, req)string, stringstring|nilSynchronous RPC via message broker (Pro)
ntop.sendKafkaMessage(topic, msg)string, stringnilSend to Kafka topic (Pro+Kafka)
ntop.sendMail(params)tablebooleanSend email via SMTP (if compiled)
ntop.getInfluxDBInternalDBName()stringInternal InfluxDB name
ntop.setInfluxDBInternalDBName(name)stringnilSet internal InfluxDB name
ntop.isInfluxDBInternalAvailable()booleanTrue if internal InfluxDB ready
ntop.setInfluxDBInternalAvailable(v)booleannilSet internal InfluxDB availability
ntop.elasticsearchConnection()table|nilElasticsearch connection details
ntop.toggleNewDeleteTrace(v)boolnilDebug: trace new/delete calls
ntop.setMacDeviceType(mac, type)string, integernilSet device type for MAC address
ntop.checkNetworkPolicy(ip)stringtableEvaluate network policy for IP

Quick-Reference: Common REST API patterns

Pattern 1 — Simple GET with interface context

lua
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
local rest_utils = require("rest_utils")
require "lua_utils"

local ifid = _GET["ifid"]
if isEmptyString(ifid) then
   rest_utils.answer(rest_utils.consts.err.invalid_interface)
   return
end
interface.select(ifid)
local data = interface.getStats()
rest_utils.answer(rest_utils.consts.success.ok, data)

Pattern 2 — Admin-only POST endpoint

lua
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
local rest_utils = require("rest_utils")
require "lua_utils"
local json = require("dkjson")

if not isAdministrator() then
   rest_utils.answer(rest_utils.consts.err.not_granted)
   return
end

local body = json.decode(_POST["JSON"] or "{}")
local username = body and body["username"]
if isEmptyString(username) then
   rest_utils.answer(rest_utils.consts.err.invalid_args)
   return
end

local ok = ntop.addUser(username, body["full_name"] or "", body["password"] or "",
                        "unprivileged", "", "")
if ok then
   rest_utils.answer(rest_utils.consts.success.ok)
else
   rest_utils.answer(rest_utils.consts.err.internal_error)
end

Pattern 3 — Redis-backed configuration

lua
local CONF_KEY = "ntopng.prefs.my_feature"
local json = require("dkjson")
require "lua_utils"
local rest_utils = require("rest_utils")

-- GET: read config
local raw = ntop.getCache(CONF_KEY)
local conf = json.decode(raw or "{}") or {}
rest_utils.answer(rest_utils.consts.success.ok, conf)
lua
-- POST: write config
local body = json.decode(_POST["JSON"] or "{}")
ntop.setCache(CONF_KEY, json.encode(body))
rest_utils.answer(rest_utils.consts.success.ok)

Pattern 4 — Hash-based per-user settings

lua
-- Store
ntop.setHashCache("ntopng.user." .. username, "my_setting", value)

-- Read
local v = ntop.getHashCache("ntopng.user." .. username, "my_setting")

Generated from src/LuaEngineNtop.cpp_ntop_reg[] table.