You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Wireshark Lua API:如何维护特定于数据包文件的变量?

Wireshark Lua Dissector:定义数据包文件专属全局变量的方法

问题描述

用户提供的Lua dissector代码片段:

local proto = Proto("myproto", "my proto")

local n_visited = 0

function proto.dissector(tvbuf, pinfo, tree)
    -- ...
    -- ...

    if not pinfo.visited then
        n_visited = n_visited + 1
    end

    -- ...
    -- ...
end

DissectorTable.get("tcp.port"):add(12345, proto)

由于Wireshark仅加载一次dissector模块,模块内的私有全局变量n_visited会在多个数据包文件之间共享,需要找到定义特定于数据包文件的全局变量的方法。

可行解决方案

方案1:利用pinfo的私有存储(推荐)

Wireshark的pinfo(PacketInfo对象)提供了private_table属性,可用于存储当前数据包上下文的专属数据,不同数据包文件的private_table相互独立,文件关闭后数据会自动清空。

修改后的代码示例:

local proto = Proto("myproto", "my proto")

function proto.dissector(tvbuf, pinfo, tree)
    -- 初始化当前数据包文件的计数变量
    if not pinfo.private_table.myproto_visited_count then
        pinfo.private_table.myproto_visited_count = pinfo.visited and 0 or 1
    else
        if not pinfo.visited then
            pinfo.private_table.myproto_visited_count = pinfo.private_table.myproto_visited_count + 1
        end
    end

    -- 可按需使用该变量,比如打印或添加到协议树
    if not pinfo.visited then
        print("当前文件未访问包计数:", pinfo.private_table.myproto_visited_count)
    end

    -- ... 原有的协议解析逻辑 ...
end

DissectorTable.get("tcp.port"):add(12345, proto)

方案2:监听文件加载/重置事件

通过注册Listener监听数据包文件的加载、重置事件,在事件触发时重置变量,确保变量仅对应当前打开的数据包文件。

代码示例:

local proto = Proto("myproto", "my proto")
local n_visited = 0

-- 注册全局监听器,监听frame事件以捕获文件变化
local file_listener = Listener.new(nil, "frame")

-- 每次文件加载、重置时触发该函数,清空计数
function file_listener.reset()
    n_visited = 0
end

function proto.dissector(tvbuf, pinfo, tree)
    if not pinfo.visited then
        n_visited = n_visited + 1
        print("当前文件未访问包计数:", n_visited)
    end

    -- ... 原有的协议解析逻辑 ...
end

DissectorTable.get("tcp.port"):add(12345, proto)

内容的提问来源于stack exchange,提问作者pynexj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 16:31:17