文章链接:https://codemouse.online/archives/2020-06-30-21-08-22
由于结构体写在结构体里面容易出现结构体内存对齐问题,需要将对齐值改为1,防止出错。
#pragma pack(1) //设置对齐数udp报文头定义:
struct udphdr { unsigned short sport; unsigned short dport; unsigned short length; unsigned short check; };tcp报文头定义:
struct tcphdr { unsigned short sport; unsigned short dport; unsigned int seq; unsigned int ack; unsigned char hdrlen:4 resc:4; unsigned char cwr:1, ece:1, urg:1, ack:1, psh:1, rst:1, syn:1, fin:1; unsigned short wsize; unsigned short check; unsigned short upoint; unsigned char options[0]; }; #define ETH_LENGTH 6 struct ethhdr { unsigned char dest[ETH_LENGTH]; unsigned char src[ETH_LENGTH]; unsigned short proto; };以太网帧格式与ip头格式的定义:
struct iphdr { unsigned char version:4, hdrlen:4; unsigned char tos; // unsigned short tot_len; unsigned short id; unsigned short flag:3, offset:13; unsigned char ttl; unsigned char proto; unsigned short check; unsigned int sip; unsigned int dip; };udp数据报定义:
struct udppkt { struct ethhdr eh; struct iphdr ip; struct udphdr udp; unsigned char body[0]; };tcp数据报定义:
struct tcppkt { struct ethhdr eh; struct iphdr ip; struct tcphdr tcp; unsigned char body[0]; };