C++ 将字符串数据包转换为 iphdr语言 - 字符串数据包的格式应该是什么?

C++ Converting string packet to iphdr - what should be the format of string packet?

本文关键字:字符串 数据包 格式 是什么 语言 转换 iphdr C++      更新时间:2023-10-16

所以我有这样一行代码:

struct iphdr *ip_header = (struct iphdr*) packet.c_str();

来自 IP.H:

struct iphdr
{
#if __BYTE_ORDER == __LITTLE_ENDIAN
unsigned int ihl:4;
unsigned int version:4;
#elif __BYTE_ORDER == __BIG_ENDIAN
unsigned int version:4;
unsigned int ihl:4;
#else
# error    "Please fix <bits/endian.h>"
#endif
u_int8_t tos;
u_int16_t tot_len;
u_int16_t id;
u_int16_t frag_off;
u_int8_t ttl;
u_int8_t protocol;
u_int16_t check;
u_int32_t saddr;
u_int32_t daddr;
/*The options start here. */
};

我使用 wireshark 捕获了一个 DNS 数据包,并得到了此示例数据包:

0000   e0 8e 3c 1c c0 07 ac bc 32 83 84 d9 08 00 45 00
0010   00 3f 51 45 00 00 40 11 aa b3 c0 a8 fe 65 c0 a8
0020   fe fe 0e 76 00 35 00 2b d5 1c 9c 0a 01 00 00 01
0030   00 00 00 00 00 00 03 77 77 77 06 67 6f 6f 67 6c
0040   65 03 63 6f 6d 02 70 68 00 00 01 00 01

我删除了 eth 标头,所以我只剩下这个:

0000   45 00
0010   00 3f 51 45 00 00 40 11 aa b3 c0 a8 fe 65 c0 a8
0020   fe fe 0e 76 00 35 00 2b d5 1c 9c 0a 01 00 00 01
0030   00 00 00 00 00 00 03 77 77 77 06 67 6f 6f 67 6c
0040   65 03 63 6f 6d 02 70 68 00 00 01 00 01

第一部分(45 00 00 3f 51 45 00 00 40 11(翻译为:

45     0100 .... = Version: 4
.... 0101 = Header Length: 20 bytes (5)
00     Differentiated Services Field: 0x00 (DSCP: CS0, ECN: Not-ECT)
00 3f  Total Length: 63
51 45  Identification: 0x5145 (20805)
00 00  Flags: 0x00
Fragment offset: 0
40     Time to live: 64
11     Protocol: UDP (17)

我的问题是:字符串变量数据包的格式应该是什么?我试过这个:

std::string packet = "45 00 00 3f 51 45 00 00 40 11";

但是对于ip_header>协议,我得到48 个"0">而不是 17。

我也想知道,为什么协议不在第 9 个字节上?我假设它应该在 9 日基于 iphr 的结构。

非常感谢任何人的帮助。多谢!

你的基本假设有一些问题。您正在使用一个字符串,并且假设如果将其转换为某个结构定义,它将自动(并且自动神奇地(将其转换为该结构定义的正确二进制表示形式。事实并非如此。假设您有一个结构'struct Test { unsigned int t; }'和一个字符串'std::string st = "12"'。你做'struct Test *pt = st.c_str();'."12"的 ASCII 表示形式将0x31 0x32,因此现在 *pt 指向以 31 32 开头的内存位置。将其转换为整数(假设我们有一个大端系统,并假设无符号 int 是两个字节(会导致 0x3132(十进制 12594(。