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

时间:2017-08-02 10:11:36

标签: c++ udp hex protocols wireshark

所以我有这行代码:

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-&gt;协议,我得到 48&#39; 0&#39; 而不是17。

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

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

1 个答案:

答案 0 :(得分:1)

您的基本假设存在一些问题。您正在使用字符串,并假设如果将其转换为某个结构定义,它将自动(并自动地)将其转换为该结构定义的正确二进制表示。不是这种情况。我们假设您有一个结构'struct Test { unsigned int t; }'和一个字符串'std::string st = "12"'。你做'struct Test *pt = st.c_str();'。 &#34; 12&#34;的ASCII表示将是0x31 0x32所以现在* pt指向以31开头的内存位置。将其转换为整数(假设我们有一个big-endian系统并假设unsigned int是两个字节)导致0x3132(十进制12594)。

相关问题