2017-08-02 16 views
0

所以我有这行代码:C++将字符串数据包转换为iphdr - 字符串数据包的格式应该是什么?

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 51 3F 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日基于iphdr的结构。

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

+0

数据包不应包含* text *。 Wireshark中看到的是二进制数据的十六进制表示。数据本身不包含这些字符。 (很像“小猫”一词不是小猫。) – molbdnilo

回答

0

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

相关问题