我正在lua编写一个Wireshark协议解析器。它解析的协议包含crc16校验和。解剖员应该检查crc是否正确。计算lua中bytearray/userdata的crc16
我发现用C编写的crc16实现已经与lua包装代码here。我已成功编译并运行它(例如crc16.compute("test")
)。问题是它期望一个字符串作为输入。从wireshark,我得到一个似乎是lua类型的缓冲区userdata
。所以当我做
crc16.compute(buffer(5, 19))
Lua抱怨bad argument #1 to compute (string expected, got userdata)
。
在crc16 implementationcompute()
看起来是这样的:
static int compute(lua_State *L)
{
const char *data;
size_t len = 0;
unsigned short r, crc = 0;
data = luaL_checklstring(L, 1, &len);
for (; len > 0; len--)
{
r = (unsigned short)(crc >> 8);
crc <<= 8;
crc ^= crc_table[r^*data];
data ++;
}
lua_pushinteger(L, crc);
return 1;
}
看来luaL_checklstring
失败。所以我想我可能需要将输入转换成一个lua字符串,我不确定它是否有效,因为我输入的所有字节都不一定是可打印的字符。或者我需要调整上面的代码,以便它接受类型userdata的输入。我发现lua_touserdata()
,但这似乎返回像一个指针。所以我需要第二个参数的长度,对吧?
我不一定需要使用此实现。任何接受用户数据的lua的crc16实现都可以很好地解决问题。
也许wireshark提供了一种将缓冲区转换为Lua字符串的方法?也许'__tostring'?如果是这样,你可以使用'lua_tostring'而不是'luaL_checklstring'。 – lhf
如果我做'uint8_t * data =(uint8_t *)lua_tostring(L,1); lua_pushinteger(L,data [0]);'然后wireshark崩溃。如果我做'uint8_t * data =(uint8_t *)lua_tolstring(L,1,&len); lua_pushinteger(L,len);'那么我会得到'0'长度 –
另外,我的数据可能包含多个零字节,而lua字符串在第一个零终止,对吗?不会在第一个零终止吗? –