Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of sequence of bytes to ASCII string in lua

I am trying to write custom dissector for Wireshark, which will change byte/hex output to ASCII string.

I was able to write the body of this dissector and it works. My only problem is conversion of this data to ASCII string.

Wireshark declares this data to be sequence of bytes. To Lua the data type is userdata (tested using type(data)). If I simply convert it to string using tostring(data) my dissector returns 24:50:48, which is the exact hex representation of bytes in an array.

Is there any way to directly convert this byte sequence to ascii, or can you help me convert this colon separated string to ascii string? I am totally new to Lua. I've tried something like split(tostring(data),":") but this returns Lua Error: attempt to call global 'split' (a nil value)


Using Jakuje's answer I was able to create something like this:

function isempty(s)
  return s == nil or s == ''
end
data = "24:50:48:49:4A"
s = ""
for i in string.gmatch(data, "[^:]*") do
    if not isempty( i ) then
        print(string.char(tonumber(i,16)))
        s = s .. string.char(tonumber(i,16))
    end
end
print( s )

I am not sure if this is effective, but at least it works ;)

like image 842
Soul Reaver Avatar asked Sep 02 '25 09:09

Soul Reaver


2 Answers

There is no such function as split in Lua (consulting reference manual is a good start). You should use probably string.gmatch function as described on wiki:

data = "24:50:48"
for i in string.gmatch(data, "[^:]*") do
  print(i)
end

(live example)

Further you are searching for string.char function to convert bytes to ascii char.

like image 150
Jakuje Avatar answered Sep 04 '25 23:09

Jakuje


You need to mark range of bytes in the buffer that you're interested in and convert it to the type you want:

data:range(offset, length):string()
-- or just call it, which works the same thanks to __call metamethod
data(offset, length):string()

See TvbRange description in https://wiki.wireshark.org/LuaAPI/Tvb for full list of available methods of converting buffer range data to different types.

like image 37
Oleg V. Volkov Avatar answered Sep 05 '25 00:09

Oleg V. Volkov