gpt4 book ai didi

c - 带有填充的结构的补码校验和?

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

我正在编写一些使用 IP/UDP 数据包进行通信的代码。因此,我需要能够计算两个 header 的校验和。我的头部结构如下:

/* Internet protocol v4 header */
typedef struct {
uint8_t ip_ver_hl; /* ip v4, header length = 5 32 bit words */
uint8_t ip_tos; /* type of service */
uint16_t ip_len; /* total length in bytes (ip header + data) */
uint16_t ip_id; /* identification */
uint16_t ip_off; /* fragment offset field */
#define IP_DF 0x4000 /* dont fragment flag */
#define IP_MF 0x2000 /* more fragments flag */
#define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
uint8_t ip_ttl; /* time to live */
uint8_t ip_proto; /* layer 4 protocol */
uint16_t ip_checksum; /* ip header checksum */
uint32_t ip_src; /* ip source address */
uint32_t ip_dst; /* ip destination addresss */
} ttev_ip_header_t;

/* Pseudo header used to calculate udp checksum */
typedef struct {
uint32_t ip_src; /* ip source address */
uint32_t ip_dst; /* ip destination addresss */
uint8_t zero; /* placeholder = 0 */
uint8_t ip_proto; /* layer 4 protocol = udp */
uint16_t udp_len; /* total length in bytes (header + data) */
} ttev_udp_pseudo_t;

/* User datagram protocol header */
typedef struct {
uint16_t udp_src_port; /* source port */
uint16_t udp_dst_port; /* destination port */
uint16_t udp_len; /* total length in bytes (udp header + data) */
uint16_t udp_checksum; /* udp header/data checksum */
} ttev_udp_header_t;

现在我的实际通用校验和函数运行良好。但是,由于结构未打包,我不会因为在 header 上校验和时出现错误而在结构成员之间可能存在填充吗?我想避免使用 attribute((packed)) 以保持可移植性。

除了对结构中每个单独的 16 位组进行校验和之外,还有其他选择吗?

最佳答案

UDP 和 IP 数据包 header 的结构与 C 的对齐方式相匹配。因此,只要 uint8_tuint16_t 实际上(分别)是 8 位和 16 位宽,那么就永远不会在整个结构会很好。

基本上,对齐意味着每个字段都从与其大小或机器的自然字大小(以较小者为准)相匹配的边界开始。结构本身被填充为所有字段中最大对齐的倍数。

关于c - 带有填充的结构的补码校验和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26977659/

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