我在上计算机和网络安全课。我们正在写一个包欺骗。我可以从网上下载并使用它,但我更喜欢自己写东西。下面是我用来表示我basing off of the wikipedia article的ip头的结构。我正在尝试发送icmp ping数据包。我已经成功地完成了这项工作,但只有在将ip头长度的值分配给version字段之后,反之亦然。不知怎么的,我把结构设置错了,或者我把值赋值错了,我不知道我做错了什么。

struct ip_header
{
    uint8_t version : 4 // version
        , ihl : 4; // ip header length
    uint8_t dscp : 6 // differentiated services code point
        , ecn : 2; // explicit congestion notification
    uint16_t total_length; // entire packet size in bytes
    uint16_t identification; // a unique identifier
    uint16_t flags : 3 // control and identify fragments
        , frag_offset : 13; // offset of fragment relative to the original
    uint8_t ttl; // how many hops the packet is allowd to travel
    uint8_t protocol; // what protocol is in use
    uint16_t checksum; // value used to determine bad packets
    uint32_t src_ip; // where the packet is form
    uint32_t dest_ip; // where the packet is going
};

如果像下面这样分配versionihl,wireshark会报告一个标题错误,“假的IPV4版本(0,必须是4)”。
char buffer[1024];
struct ip_header* ip = (struct ip_header*) buffer;
ip->version = 4;
ip->ihl = 5;

但是,在更改为下面的列表之后,ICMP请求就可以顺利完成了。
char buffer[1024];
struct ip_header* ip = (struct ip_header*) buffer;
ip->version = 5;
ip->ihl = 4;

我试着把htons放在数字周围,但这似乎没有任何用处。我错过了什么?

最佳答案

你只需要纠正你的结构末端。查看<netinet/ip.h>文件中定义的IP头结构:

  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
    uint8_t tos;
    uint16_t tot_len;
    uint16_t id;
    uint16_t frag_off;
    uint8_t ttl;
    uint8_t protocol;
    uint16_t check;
    uint32_t saddr;
    uint32_t daddr;
    /*The options start here. */
  };

09-30 13:37