gpt4 book ai didi

c - 一个ip头的布局和网络编程

转载 作者:太空宇宙 更新时间:2023-11-04 06:50:25 27 4
gpt4 key购买 nike

我正在上计算机和网络安全类(class)。我们正在编写一个数据包欺骗器。我可以从互联网上下载一个并使用它,但我更喜欢自己编写这些东西。下面是我用来表示 ip header 的结构,我是 basing off of the wikipedia article .我正在尝试发送一个 icmp ping 数据包。我已经成功完成了,但是只有在将 ip header 长度的值分配给版本字段之后,反之亦然。我以某种方式设置了我的结构错误,或者我分配了错误的值,而且我不确定我做错了什么。

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 会报告标题错误,“Bogus IPV4 version (0, must be 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. */
};

关于c - 一个ip头的布局和网络编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52286967/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com