本文介绍了在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:

通过以下方式调用:

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?

推荐答案

来自:

使用'!'作为使打包结构与平台无关的第一个格式字符。它强制使用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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:08