gpt4 book ai didi

C结构对齐和网络协议(protocol)头

转载 作者:太空宇宙 更新时间:2023-11-04 04:47:13 26 4
gpt4 key购买 nike

Solaris 10 SPARC
Sun Studio C 编译器 12.3

在 SPARC64 机器上,如果您访问一个在相关 4 或 8 字节边界上未正确对齐的变量,您将获得核心转储。这需要编码人员跳过几个环节来满足这一要求,(但也会让您编写可移植的代码)。

如果我们有一个模拟网络协议(protocol)头的 C 结构,(即这 16 位是一个端口,这 8 位是标志等),如果我们然后使用对齐指令来适应SPARC64 处理器,这是否仍然保留字节映射,或者一切都会中断。是否存在从结构布局中隐藏字节存储实现的逻辑。

typedef struct TCPHdr_
{
uint16_t th_sport; /**< source port */
uint16_t th_dport; /**< destination port */
uint32_t th_seq; /**< sequence number */
uint32_t th_ack; /**< acknowledgement number */
uint8_t th_offx2; /**< offset and reserved */
uint8_t th_flags; /**< pkt flags */
uint16_t th_win; /**< pkt window */
uint16_t th_sum; /**< checksum */
uint16_t th_urp; /**< urgent pointer */
} TCPHdr;

像这样对齐:

typedef struct TCPHdr_
{
uint16_t th_sport __attribute__((aligned(8))); /**< source port */
uint16_t th_dport __attribute__((aligned(8))); /**< destination port */
uint32_t th_seq __attribute__((aligned(8))); /**< sequence number */
uint32_t th_ack __attribute__((aligned(8))); /**< acknowledgement number */
uint8_t th_offx2 __attribute__((aligned(8))); /**< offset and reserved */
uint8_t th_flags __attribute__((aligned(8))); /**< pkt flags */
uint16_t th_win __attribute__((aligned(8))); /**< pkt window */
uint16_t th_sum __attribute__((aligned(8))); /**< checksum */
uint16_t th_urp __attribute__((aligned(8))); /**< urgent pointer */
} TCPHdr;

主要是查询这样的代码:

SET_PKT_LEN(p, sizeof(IPV6Hdr) + sizeof(TCPHdr) + payload_len);

p1->tcph = (TCPHdr *)raw_tcp;

其中原始字节被转换为结构或 sizeof() 测试结构的大小。它仍然有效还是新结构无法映射网络字节?

最佳答案

您可以将未对齐的结构转换为其对齐版本,但数据会出错。您需要手动将数据放到内存中的正确位置。例如。函数 *unaligned_to_aligned* 可以逐字段复制数据。它可以使用 union 来避免核心转储。使用来自网络的原始数据时,请考虑 endianness .网络协议(protocol)和您的平台在内存中可以有不同的数字表示,您可能必须更改 *int*s、*short*s 等中的字节顺序。

关于C结构对齐和网络协议(protocol)头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19646403/

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