我有一个程序可以检查某些变量字段的条件,比如
if(tostring(field) == '0') then {do something}
if(tostring(field) == '1') then {do something}
if(tostring(field) == '2') then {do something}
但是,我认为lua将'0'和'1'解释为TRUE / FALSE值,而不是正确检查相应的if条件。条件在字段=='2'条件下正确执行
我怎样才能克服这种情况?如何使它适用于检查条件'0'和'1'?
提前谢谢!
如果您想知道我为什么标记wireshark,if检查条件是检查pcap文件中的字段
我的lua代码供参考如下:
#!/usr/bin/lua
do
local pkts = 0
local stat = {}
local file = io.open("luawrite","w")
local function init_listener()
local tap = Listener.new("wlan")
local src_addr = Field.new("wlan.sa")
local type = Field.new("wlan.fc.type")
local sub_type = Field.new("wlan.fc.subtype")
local frame_length = Field.new("frame.len")
local data_rate = Field.new("wlan.data_rate")
function tap.reset()
pkts = 0;
end
function tap.packet(pinfo, tvb)
local client = src_addr()
local stype = sub_type()
local ty = type()
local ts = tostring(pinfo.rel_ts)
local fl = frame_length()
rate = data_rate()
if(tostring(ty) == '0') then
file:write(tostring(ts), "\t", tostring(fl), "\t", tostring(rate), "\n")
end
end
end
init_listener()
end
条件我指的是最后一行的第7行。如果我给条件tostring(ty)=='2',它可以正常工作。
答案 0 :(得分:1)
来自manual:
控制结构的条件表达式可以返回任何值。 假和零都被认为是假的。所有值都不等于零 和false被认为是真的(特别是数字0和 空字符串也是如此)。
数字0和空字符串都计算为true,因此绝对不会将字符串“0”误认为是false。我可能会避免重新定义type
。另外,我认为frame_type返回一个数字,这样你就可以摆脱条件中的tostring()
。
do
local pkts = 0
local stat = {}
local file = io.open("luawrite","w")
local function init_listener()
local tap = Listener.new("wlan")
local src_addr = Field.new("wlan.sa")
-- Changed function from type to frame_type
local frame_type = Field.new("wlan.fc.type")
local sub_type = Field.new("wlan.fc.subtype")
local frame_length = Field.new("frame.len")
local data_rate = Field.new("wlan.data_rate")
function tap.reset()
pkts = 0;
end
function tap.packet(pinfo, tvb)
local client = src_addr()
local stype = sub_type()
local ty = frame_type()
local ts = tostring(pinfo.rel_ts)
local fl = frame_length()
rate = data_rate()
-- skip the tostring
if ty == 0 then
file:write(tostring(ts), "\t", tostring(fl), "\t", tostring(rate), "\n")
end
end
end
init_listener()
end
如果所有其他方法都失败了,请尝试写一条线而不管帧类型如何,并用它写入帧类型:
function tap.packet(pinfo, tvb)
local client = src_addr()
local stype = sub_type()
local ty = frame_type()
local ts = tostring(pinfo.rel_ts)
local fl = frame_length()
rate = data_rate()
file:write(tostring(ty), "\t", tostring(ts), "\t", tostring(rate), "\n")
end
然后您可以看到您正在接收的帧类型。
答案 1 :(得分:1)
正如Corbin所说,它肯定不会将“0”和“1”解释为TRUE / FALSE。 Wireshark运行库存Lua解释器,Lua只考虑nil
并将false
的布尔值视为false 值。当然,你并没有真正检查它们是否为假值,你正在对“wlan.fc.type”字段值的字符串ifing值与字符串“0”或字符串“1”进行字符串比较“ 管他呢。你获得的“wlan.fc.type”字段的实际值是一个数字,因此Corbin说没有必要将它转换为字符串和字符串 - 将它与字符串“0”或其他任何东西进行比较......将它们作为数字进行比较。
无论如何,对它们进行字符串化也应该有效(效率较低),因此很可能在捕获中没有wlan.fc.type为0的802.11数据包。 wlan.fc.type为0是管理帧,1是控制帧,2是数据帧。所以你很可能只捕获802.11数据包,这就是为什么你将字符串-ified wlan.fc.type与字符串“2”的比较成功的原因。
找到的一种方法是在wireshark中打开捕获文件,并为“wlan.fc.type == 0”输入显示过滤器,并查看是否显示了任何数据包。如果没有,那么你没有任何管理包。