gpt4 book ai didi

c - 使用结构在C中解析数据包

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:37 24 4
gpt4 key购买 nike

我有一个来自线路的数据包,我有一个表示数据包的结构:

typedef struct {
uint8_t packetType;
uint8_t remainingLength;
uint16_t protocolNameLength;
char protocolName[20];
uint8_t protocolLevel;
uint8_t connectFlags;
uint16_t keepAlive;
} Connect;

我有以下解析数据包的 C 代码:

void decodePacket(char *packet) {
Connect *connect = NULL;
connect = (Connect *) packet;
// Here I access the different fields of the packet using the connect struct
printf("Protocol Name is %s\n", connect->protocolName);
}

在上面的协议(protocol)中,当字符串从线路传入时,它们不是空终止的,因此当我打印协议(protocol)名称时,我会得到一些奇怪的字符。有没有办法在不改变协议(protocol)的情况下解决这个问题?

此外,如果协议(protocol)名称 > 20,字符缓冲区将溢出。有没有办法解决这个问题?我是否需要放弃这种解析数据包的方法,只使用索引并手动解析数据包的每个字节?

谢谢

最佳答案

将数据包转换为结构非常危险,因为您几乎无法控制结构在内存中的实际对齐方式。

您需要阅读 C 结构打包的失落艺术:http://www.catb.org/esr/structure-packing/

关于c - 使用结构在C中解析数据包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43702877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com