以下是ipv4首部的数据结构:
/* IPv4 首部 */
typedef struct ip_header {
u_char ver_ihl; // 版本 (4 bits) + 首部长度 (4 bits)
u_char tos; // 服务类型(Type of service)
u_short tlen; // 总长(Total length)
u_short identification; // 标识(Identification)
u_short flags_fo; // 标志位(Flags) (3 bits) + 段偏移量(Fragment offset) (13 bits)
u_char ttl; // 存活时间(Time to live)
u_char proto; // 协议(Protocol)
u_short crc; // 首部校验和(Header checksum)
ip_address saddr; // 源地址(Source address)
ip_address daddr; // 目的地址(Destination address)
u_int op_pad; // 选项与填充(Option + Padding)
}ip_header;
通过ip首部的ver_ihl(首部长度)计算出tcp首部的位置
ip_len = (ip_header->ver_ihl & 0xf) * 4;
tcp_hdr = (tcp_header*)((u_char*)ip_header + ip_len);
以下是TCP首部的数据结构:
//TCP首部
typedef struct tcp_header
{
unsigned short src_port; //源端口号
unsigned short dst_port; //目的端口号
unsigned int seq_no; //序列号
unsigned int ack_no; //确认号
#if LITTLE_ENDIAN
unsigned char reserved_1 : 4; //保留6位中的4位首部长度
unsigned char thl : 4; //tcp头部长度
unsigned char flag : 6; //6位标志
unsigned char reseverd_2 : 2; //保留6位中的2位
#else
unsigned char thl : 4; //tcp头部长度
unsigned char reserved_1 : 4; //保留6位中的4位首部长度
unsigned char reseverd_2 : 2; //保留6位中的2位
unsigned char flag : 6; //6位标志
#endif
unsigned short wnd_size; //16位窗口大小
unsigned short chk_sum; //16位TCP检验和
unsigned short urgt_p; //16为紧急指针
}tcp_hdr;
以下是一段tcp/ip数据包
f8 98 ef 71 65 d9 8c ec 4b be 10 52 08 00 45 00
00 28 7c ce 40 00 40 06 00 00 c0 a8 59 7a 79 1d
1c 9d ce f7 00 50 55 4e 06 7b 15 41 b6 ad 50 10
04 02 af f7 00 00
1-14字节是以太网mac帧的帧头长度,14=6目的地址+6源地址+2类型说明。
15字节是ip首部的版本好和首部长度 解析出版本号为4,首部长度为5,再根据公式20= (5 & 0xf) * 4 算出ip首部长度为20.
20+14 = 34 也就是35字节是tcp首部地址
详细说明的链接地址https://www.cnblogs.com/larry-luo/p/10983633.html
tcp包头后的有效负载(data)里解析开头的5个字节来判断应用层协议是什么类型(https或者普通数据)
如果是以下结构则说明是https
struct ssl_record
{
unsigned char type;
unsigned char ma_version;
unsigned char mi_version;
short length;
};
type:SSL高层协议
20 (0x14):change cipher spec协议
21 (0x15):alert协议
22 (0x16):handshake协议
23 (0x17):application data协议
version:使用的SSL协议的版本号。两个字节,表示major版本和minor版本。SSL 3.0就是0x0300。TLS 1.2是0x0303,TLS 1.3是0x0304 (3,4)
length:高层协议消息的字节长度(同一个类型的多个高层协议消息可以属于同一个SSL记录)。最大值不应该超过16383。