c - Ip 结构 C 参数

标签 c sockets struct

我开始了一场原始套接字的冒险,我发现了一个我不明白的 ip header ,我的疑问是

  • hdrlen:4

This two points four are used for what?

  • 属性((打包));

What is this attribute?

struct iphdr {
    uint8_t   hdrlen:4;
    uint8_t   version:4;
    uint8_t   ecn:2;       // Explicit Congestion Notification - RFC 3168
    uint8_t   dscp:6;      // DiffServ Code Point
    uint16_t  length;
    uint16_t  ident;
    uint16_t  fragoff:13;
    uint16_t  flags:3;
    uint8_t   ttl;
    uint8_t   protocol;
    uint16_t  checksum;
    uint32_t  srcip;
    uint32_t  dstip;
    uint32_t  options[ ];  // Present if hdrlen > 5
} __attribute__((__packed__));

最佳答案

此结构代表将通过网络发送的数据包,因此您不想浪费一点空间(因为每一位都需要通过“线路”发送)。

field_name:field_width 语法声明 bit field ,所以 uint8_t hdrlen:4; 意味着您实际上只需要 4 位来存储“ header 长度”值(但编译器会确保该值被复制到 uint8_t(一个字节)当您读取字段值时)。

__attribute__((__packed__)) 语法告诉编译器忽略 usual alignment requirements for structs 。有时需要编译器在结构体字段之间插入填充,以确保对结构体中字段的有效内存访问。例如,如果您在 uint8_t 之后有一个 uint64_t,编译器会在两个字段之间插入填充(垃圾),以确保 uint64_t > 从 8 字节边界开始(即指针地址的最后 3 位全为零)。

正如您所看到的,所有这些位调整和打包都已完成,因此该结构中没有浪费空间,并且通过网络发送的每个位都是有意义的。

关于c - Ip 结构 C 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31121057/

相关文章:

c - C题中的多线程编程

c - 是否有支持 `printk()` 的 `va_list` 函数?

进程last-request-cpu的PHP-FPM池状态

python - 使用 Python 连接到 SMTP(SSL 或 TLS)

xml - 如何将 XML 属性添加到 Go 中的元素?

c - c语言中的%d和%*d有什么区别?

c++ - Boost 连接后从 TCP 服务器访问 TCP 客户端 IP 地址 + 端口

java - 如何在ssh上测试客户端和服务器程序?

ios - 类型 '()' 不能符合 'View' ;只有结构/枚举/类类型可以符合协议(protocol);使用 SwiftUI 调用函数

c - 尝试创建结构体数组时运行时检查失败 #2