秦悦明的运维笔记

tcp连接建立和断开

1. 建立连接

又叫三次握手,老外叫three way handshake,很好记,分别发三个包,syn,syn+ack,ack
用tcpdump出来就是如下的形式:

1
2
3
4
5
6
7
8
10:24:00.265744 IP (tos 0x10, ttl 64, id 21567, offset 0, flags [DF], proto TCP (6), length 64)
192.168.3.10.58544 > 114.215.206.177.5555: Flags [S], cksum 0xf35a (correct), seq 1754109131, win 65535, options [mss 1460,nop,wscale 5,nop,nop,TS val 811537995 ecr 0,sackOK,eol], length 0
10:24:00.286693 IP (tos 0x0, ttl 52, id 0, offset 0, flags [DF], proto TCP (6), length 60)
114.215.206.177.5555 > 192.168.3.10.58544: Flags [S.], cksum 0xafc3 (correct), seq 2349913793, ack 1754109132, win 28960, options [mss 1312,sackOK,TS val 2088043701 ecr 811537995,nop,wscale 7], length 0
10:24:00.286749 IP (tos 0x10, ttl 64, id 762, offset 0, flags [DF], proto TCP (6), length 52)
192.168.3.10.58544 > 114.215.206.177.5555: Flags [.], cksum 0x3f00 (correct), seq 1, ack 1, win 4103, options [nop,nop,TS val 811538016 ecr 2088043701], length 0

2.断开连接

又叫4次挥手,多了一次是因为tcp是双向全双工的协议,要两边都关一下,然后确认。
但我用telnet测试的时候抓到的都是3个报文,并没有第二个的ack包。

1
2
3
4
5
6
7
8
10:24:13.326683 IP (tos 0x10, ttl 64, id 41433, offset 0, flags [DF], proto TCP (6), length 52)
192.168.3.10.58544 > 114.215.206.177.5555: Flags [F.], cksum 0x0c2b (correct), seq 1, ack 1, win 4103, options [nop,nop,TS val 811551028 ecr 2088043701], length 0
10:24:13.347347 IP (tos 0x0, ttl 52, id 53768, offset 0, flags [DF], proto TCP (6), length 52)
114.215.206.177.5555 > 192.168.3.10.58544: Flags [F.], cksum 0xe848 (correct), seq 1, ack 2, win 227, options [nop,nop,TS val 2088056762 ecr 811551028], length 0
10:24:13.347436 IP (tos 0x10, ttl 64, id 47236, offset 0, flags [DF], proto TCP (6), length 52)
192.168.3.10.58544 > 114.215.206.177.5555: Flags [.], cksum 0xd910 (correct), seq 2, ack 2, win 4103, options [nop,nop,TS val 811551048 ecr 2088056762], length 0

3. tcp头部信息图

1
2
3
4
5
6
7
8
9
10
11
12
0 15 31
-----------------------------------------------------------------
| source port | destination port |
-----------------------------------------------------------------
| sequence number |
-----------------------------------------------------------------
| acknowledgment number |
-----------------------------------------------------------------
| HL | rsvd |C|E|U|A|P|R|S|F| window size |
-----------------------------------------------------------------
| TCP checksum | urgent pointer |
-----------------------------------------------------------------

source port : 源端口, 1024~65535.
destination port : 目的端口,比如常见的80,22等。
sequence number: 序列号,用来将数据正确的顺序重新排序。
acknowledgment number: 确认号,tcp期望接下来收到的数据段。
rsvd: 用于建立和终止会话的控制功能。
window size: 窗口大小,发送方愿意接受窗口的大小。
tcp头部一共20个字节,相对udp还是复杂很多的,每次传数据之前要简历虚电路,就是上面的三次握手。