在Python中计算结构的CRC [英] compute CRC of struct in Python

查看:140
本文介绍了在Python中计算结构的CRC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C中的NRPE守护程序代码中具有以下结构:

I have the following struct, from the NRPE daemon code in C:

typedef struct packet_struct {
  int16_t packet_version;
  int16_t packet_type;
  uint32_t crc32_value;
  int16_t result_code;
  char buffer[1024];
} packet;

我想将此数据格式从Python发送到C守护程序。当 crc32_value 0 时计算CRC,然后将其放入结构中。我的Python代码执行以下操作:

I want to send this data format to the C daemon from Python. The CRC is calculated when crc32_value is 0, then it is put into the struct. My Python code to do this is as follows:

cmd = '_NRPE_CHECK'
pkt = struct.pack('hhIh1024s', 2, 1, 0, 0, cmd)
# pkt has length of 1034, as it should
checksum = zlib.crc32(pkt) & 0xFFFFFFFF
pkt = struct.pack('hhIh1024s', 2, 1, checksum, 0, cmd)
socket.send(....)

守护程序正在接收以下值: version = 2 type = 1 crc = FE4BBC49 result = 0

The daemon is receiving these values: version=2 type=1 crc=FE4BBC49 result=0

但它正在计算 crc = 3731C3FD

计算CRC的实际C代码是:

The actual C code to compute the CRC is:

https://github.com/KristianLyng/nrpe/blob/master/src/utils.c

通过以下方式调用:

calculate_crc32((char *)packet,sizeof(packet));

当我将这两个函数移植到Python时,得到的结果与 zlib.crc32 返回的值相同。

When I ported those two functions to Python, I get the same as what zlib.crc32 returns.

我的 struct.pack 调用正确吗?为什么我的CRC计算与服务器的计算不同?

Is my struct.pack call correct? Why is my CRC computation differing from the server's?

推荐答案

来自 Python结构文档


处理与平台无关的数据格式或省略隐式填充
字节,使用标准大小和对齐方式,而不是本机大小和
对齐方式:请参见字节顺序,大小和对齐方式以获取详细信息。

使用'!'作为使打包结构与平台无关的第一个格式字符。它强制使用big-endian,标准类型大小,并且没有填充字节。那么CRC应该是一致的。

Use '!' as the first format character to make the packed structure platform-independent. It forces big-endian, standard type sizes, and no pad bytes. Then the CRCs should be consistent.

这篇关于在Python中计算结构的CRC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆