计算机网络 - UDP/TCP、IP、MAC报文协议格式
1、计算机网络
计算机网络体系结构:
现在多是参考(c)五层协议。
每层比较常见的协议:
2、数据链路层(MAC层)
以太网V2的MAC帧格式:
MAC帧头部结构体定义:
// u_char: 1字节,8位 // u_short: 2字节,16位 // u_int: 4字节,32位 // 以太网帧数据头部 - 固定 14 个字节 typedef struct ethernet_header { u_char dest_mac[6]; // 目的地址(MAC地址) u_char src_mac[6]; // 源地址(MAC地址) u_short type;// 类型字段,用来标志上一层使用的协议,以便把MAC帧数据交给上一层的这个协议(IP:0x0800; ) }ETHERNET_HEADER;
3、网络层
IP数据包的格式:
首部长度的单位为32位字(4 bytes),所以需要 *4 计算有多少个字节长度。
总长度的单位为字节。
IP数据包头部结构体定义:
// 网络层 IP数据包 首部 - 固定 20 个字节 typedef struct ip_header { u_char ver_ihl;// 版本(4 bits)+首部长度(4 bits), 首部长度单位是32位字,所以需要 *4 计算有多少个字节 u_char tos;// 区分服务(Type of Service, 8 bits) u_short tlen;// 总长(Total Length, 16 bits),=首部长度+数据长度,最大为65535字节(2^16-1) u_short identify;// 标识(Identify, 16 bits),IP软件在存储器中维持的一个计数器,每产生一个数据包,计数器就加1(不是序号) u_short flags_fo;// 标志位(Flags 3 bits)+段偏移量(Fragment offset 13 bits) u_char ttl;// 存活时间(Time to Live, 8 bits) u_char proto;// 协议(Protocol, 8 bits),指出此数据报携带的数据是何种协议,以便目的主机IP层知道应将数据交由哪个协议进行处理 u_short crc;// 首部校验和(Header checkSum, 16 bits) u_long src_addr;// 源地址(Source Address, 32 bits) u_long des_addr;// 目的地址(Destination Address, 32 bits) //u_int op_pad; // 选项与填充(Option * Padding, 32 bits) }IP_HEADER;
4、传输层
传输层主要有UDP协议以及TCP协议。
4.1 UDP协议
UDP时面向报文的:
UDP用户数据的首部格式:
长度:UDP用户数据报的长度(首部 + 数据部分),单位为字节。
UDP数据包头部结构体定义:
// 传输层 UDP数据包 首部 - 固定首部 8 个字节 typedef struct udp_header { u_short src_port; // 源端口(Source Port, 16 bits) u_short des_port; // 目的端口(Destination Port, 16 bits) u_short len; // UDP数据包长度(Datagram Length, UDP用户数据包的长度,单位为字节) u_short crc; // 校验和(CheckSum, 16 bits) }UDP_HEADER;
4.2 TCP协议
TCP报文段的首部格式:
需要注意的是,“数据偏移”实际上就是TCP报文首部的长度,单位为 32位字(4 bytes)
TCP数据包头部结构体定义:
// 传输层 TCP数据包 首部 - 固定首部 20 个字节 typedef struct tcp_header { u_short src_port;// 源端口(2 bytes = 16 bits) u_short des_port;// 目的端口(2 bytes = 16 bits) u_int seq_num;// 序号(4 bytes = 32 bits) u_int ack_num;// 确认号(4 bytes = 32 bits) u_short hl_resv;// 首部长度(4 bits)+保留(6 bits)+ URG + ACK + PSH + RST + SYN + FIN(各 1 bit) u_short wind;// 窗口(2 bytes = 16 bits) u_short check_sum;// 校验和(2 bytes = 16 bits) u_short ur_point;// 紧急指针(2 bytes = 16 bits) //u_int op_pad; // 选项与填充(Option * Padding, 32 bits) }TCP_HEADER;