c++ - IP 头位顺序不清楚

标签 c++ c ip pcap

我阅读了 IP RFC,其中说 IP header 的前 4 位是版本。在图中还显示了第0位到第3位是版本。

https://www.rfc-editor.org/rfc/rfc791#section-3.1

但是当我查看 header 的第一个字节(使用 pcap lib 捕获)时,我看到了这个字节:

0x45

这是第 4 版 IP header ,但显然第 4 到 7 位等于 4 而不是我预期的第 0 到 3 位。

我希望在第一个字节和 0x0F 上执行按位和 0x0F 操作,但似乎我需要使用 0xF0。

我错过了什么吗?理解有误?

最佳答案

你应该阅读 Appendix B RFC 的:

Whenever an octet represents a numeric quantity the left most bit in the diagram is the high order or most significant bit. That is, the bit labeled 0 is the most significant bit. For example, the following diagram represents the value 170 (decimal).

                        0 1 2 3 4 5 6 7
                       +-+-+-+-+-+-+-+-+
                       |1 0 1 0 1 0 1 0|
                       +-+-+-+-+-+-+-+-+

这意味着一切都是正确的,除了您假设“前四位”是最不重要的,而那些是重要的。

例如在第 7 和第 8 个字节中,包含标志和片段偏移量,您可以按如下方式分隔它们(考虑伪代码,即使它正在运行 C#):

byte flagsAndFragmentHi = packet[6];
byte fragmentLo = packet[7];
bool flagReserved0 = (flagsAndFragmentHi & 0x80) != 0;
bool flagDontFragment = (flagsAndFragmentHi & 0x40) != 0;
bool flagMoreFragments = (flagsAndFragmentHi & 0x20) != 0;
int fragmentOffset = ((flagsAndFragmentHi & 0x1F) << 8) | (fragmentLo);

请注意,片段偏移的更重要(左移 8 位)部分在第一个字节中(因为 IP 在大端工作)。通常:图中左侧的位总是更重要。

关于c++ - IP 头位顺序不清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20455259/

相关文章:

c++ - 在仅适用于 Windows 的大型 MFC 应用程序中使用 Qt 会加快开发速度吗?

macos - Mac OS X 中的虚拟网络接口(interface)

c++ - glReadPixels 从后台缓冲区。浮点精度问题

c - 在链表中存储行 (c)

python - 正确地为 c 包装器制作 setup.py

c - C中的嵌套结构

安卓获取外网IP

tcp - Socat - 无缓冲

python - opencv python中图像倾斜检测的代码

c++ - 重载运算符 = 作为成员函数