当前位置:网站首页>Classic theory: detailed explanation of three handshakes and four waves of TCP protocol
Classic theory: detailed explanation of three handshakes and four waves of TCP protocol
2022-06-26 05:06:00 【JackJiang-】
1、 Preface
Even though TCP and UDP All use the same network layer (IP),TCP But to the application layer UDP A completely different service .TCP Provides a connection-oriented 、 Reliable byte stream service .
Connection-oriented means two USES TCP Application ( Usually a client and a server ) You have to create a before you can exchange data with each other TCP Connect . The process is very similar to making a phone call , Ring first , Waiting for the other party to pick up the machine and say “ feed ”, Then it's about who .
This article will explain the classic TCP The protocol establishes the connection ( So-called “3 The second handshake ”) And disconnect ( So-called “4 Second wave ”) The process of . of TCP Introduction to the authoritative theory of agreement , Please see the 《TCP/IP Detailed explanation 》 This book .( This article is published synchronously in :http://www.52im.net/thread-258-1-1.html)
2、 Exchange of learning
- Instant messaging development communication group :
215891622 [ recommend ]
- Mobile IM Develop recommended articles :《 Beginner level one is enough : Develop mobile from scratch IM》
3、 Related information
《 Technology past : Change the world TCP/IP agreement ( Precious pictures 、 Be careful with your mobile phone )》
《TCP/IP Detailed explanation - The first 17 Chapter ·TCP: Transmission control protocol 》
《TCP/IP Detailed explanation - The first 18 Chapter ·TCP Connection establishment and termination 》
《TCP/IP Detailed explanation - The first 21 Chapter ·TCP Over time and retransmission 》
《 Easy to understand - In depth understanding of TCP agreement ( On ): Theoretical basis 》
《 Easy to understand - In depth understanding of TCP agreement ( Next ):RTT、 The sliding window 、 Congestion handling 》
《 Theoretical Classics :TCP Agreed 3 Shake hands with 4 Detailed explanation of the wave process 》
《 Computer network communication protocol diagram ( Chinese Collection Edition )》
4、 Let's get to know TCP Message format
TCP/IP For details of the agreement, please refer to 《TCP/IP protocol 》 In the relevant TCP Format chapter ( Click here to view the 《TCP/IP Detailed explanation Online version 》).
Here is TCP Message format chart :

There are several fields in the above figure that need to be highlighted :
(1) Serial number :Seq Serial number , Occupy 32 position , Used to identify from TCP Byte stream sent from source to destination , Flag this when the initiator sends data .
(2) Confirm the serial number :Ack Serial number , Occupy 32 position , Only ACK Sign bit is 1 when , Verify that the ordinal field is valid ,Ack=Seq+1.
(3) Sign a : common 6 individual , namely URG、ACK、PSH、RST、SYN、FIN etc. , The specific meaning is as follows :
(A)URG: Pointer to an emergency (urgent pointer) It works .
(B)ACK: Confirm that the serial number is valid .
(C)PSH: The receiver should send this message to the application layer as soon as possible .
(D)RST: Reset connection .
(E)SYN: Initiate a new connection .
(F)FIN: Release a connection .
It should be noted that :
(A) Do not confirm the serial number Ack And in flags ACK Confused. .
(B) Confirmation party Ack= Initiator Req+1, Pairing at ends .
5、3 The handshake process is explained in detail
Three handshakes (Three-Way Handshake) Namely establishment TCP Connect , It means building a TCP When the connection , The client and server are required to send in total 3 Packages to confirm connection . stay socket Programming , This process is performed by the client connect To trigger , The whole process is shown in the figure below :

(1) The first handshake :
Client Flag location SYN Set as 1, Randomly generate a value seq=J, And send the packet to Server,Client Get into SYN_SENT state , wait for Server confirm .
(2) The second handshake :
Server Flag bit after receiving packet SYN=1 know Client Request to establish a connection ,Server Flag location SYN and ACK All are set for 1,ack=J+1, Randomly generate a value seq=K, And send the packet to Client To confirm the connection request ,Server Get into SYN_RCVD state .
(3) The third handshake :
Client After receiving the confirmation , Check ack Is it J+1,ACK Is it 1, Flag bit if correct ACK Set as 1,ack=K+1, And send the packet to Server,Server Check ack Is it K+1,ACK Is it 1, If it is correct, the connection is established successfully ,Client and Server Get into ESTABLISHED state , Complete three handshakes , And then Client And Server You can start transferring data between .
SYN attack :
During the three handshakes ,Server send out SYN-ACK after , received Client Of ACK Previous TCP A connection is called a half connection (half-open connect), here Server be in SYN_RCVD state , When I received ACK after ,Server into ESTABLISHED state .SYN Attack is Client Forging a large number of nonexistent IP Address , And to Server Constantly sending SYN package ,Server Reply confirmation package , And wait for Client The confirmation of , Because the source address does not exist , therefore ,Server Need to resend until timeout , These fake SYN The packet will take up the time of the unconnected queue , Cause normal SYN The request was dropped because the queue was full , Thus, the network is blocked or even the system is paralyzed .SYN A typical attack DDOS attack , testing SYN The way to attack is very simple , When Server There are a large number of semi connected states and sources on IP The address is random , It can be concluded that SYN attacked , Use the following command to make it active :
1 |
|
6、4 Detailed explanation of the wave process
Three handshakes are familiar , It is estimated that few people will know four waves . Four waves (Four-Way Wavehand) Termination TCP Connect , To disconnect one TCP When the connection , The client and server are required to send in total 4 Packages to confirm disconnection . stay socket Programming , This process is performed by either the client or the server close To trigger , The whole process is shown in the figure below :

because TCP Full duplex on connection , therefore , Each direction must be closed separately , The principle is that when one party completes the data transmission task , Send a FIN To terminate the connection in this direction , Receive a FIN It just means there's no data flow in this direction , No more data , But here TCP Data can still be sent on the connection , Until it's sent in that direction FIN. Active shutdown will be performed by the first party to close , The other party performs a passive shutdown , This is what is described above .
- First wave :
Client Send a FIN, Used to close Client To Server Data transfer of ,Client Get into FIN_WAIT_1 state . - Second wave :
Server received FIN after , Send a ACK to Client, Confirmation No. is receipt No +1( And SYN identical , One FIN Occupy a sequence number ),Server Get into CLOSE_WAIT state . - Third wave :
Server Send a FIN, Used to close Server To Client Data transfer of ,Server Get into LAST_ACK state . - Fourth wave :
Client received FIN after ,Client Get into TIME_WAIT state , And then send a ACK to Server, Confirmation No. is receipt No +1,Server Get into CLOSED state , Finish four waves .
There's a party on top that's shutting down , Passive closing of the other party , In practice, active shutdown will be initiated at the same time , The specific process is shown in the following figure :
The process and status are already clear in the figure above , No more details here , Refer to the previous four wave analysis steps .
7、 Conclusion
There are typical interview questions about three handshakes and four waves , It is hereby proposed that XDJM Reference :
- (1) What or process is three handshakes ? Four handshakes ? The first analysis is .
- (2) Why three handshakes to establish a connection , Closing the connection is four waves ?
This is because the server is in LISTEN State, , Received a request to establish a connection SYN After the message , hold ACK and SYN Put it in a message and send it to the client . And when you close the connection , When receiving from the other party FIN When the message , It simply means that the other party is no longer sending data but can still receive data , You may not have sent all your data to the other party , So we can immediately close, You can also send some data to the other party , Send again FIN Message to the other party to agree to close the connection now , therefore , Own side ACK and FIN It's usually sent separately .
( This article is published synchronously in :http://www.52im.net/thread-258-1-1.html)
appendix : more IM Technical articles
[1] Basic information of network programming :
《NAT Detailed explanation : The basic principle 、 Crossing technology (P2P Hole digging )、 Port aging, etc 》
《UDP What is the maximum size of a package in ?》
《Java New generation network programming model AIO Principle and Linux System AIO Introduce 》
《NIO Introduction to framework ( 3、 ... and ):iOS And MINA2、Netty4 cross-platform UDP Two way communication practice 》
《NIO Introduction to framework ( Four ):Android And MINA2、Netty4 cross-platform UDP Two way communication practice 》
>> More articles of the same kind ……
[2] of IM/ Push communication format 、 The choice of agreement :
《 Why? QQ It's using UDP Agreement, not TCP agreement ?》
《 Mobile instant messaging protocol selection :UDP still TCP?》
《 How to choose the data transmission format of instant messaging application 》
《 The strong proposal will Protobuf As your IM application data transfer format 》
《 Mobile IM The technical problems that development needs to face ( Including communication protocol options )》
《 Brief introduction of mobile terminal IM The pits developed : Architecture design 、 Communication protocol and client 》
《 Combining theory with practice : A typical set of IM Communication protocol design details 》
《58 Home real-time message system protocol design and other technical practice sharing 》
>> More articles of the same kind ……
[3] of IM/ Push the heartbeat to keep alive :
《Android Detailed explanation of process assurance : One article solves all your questions 》
《Android End message push summary : Realization principle 、 The heartbeat keeps alive 、 Problems encountered, etc 》
《 Why based on TCP The mobile end of the protocol IM We still need a heartbeat mechanism ?》
《 Wechat team original sharing :Android Version of wechat backstage to keep the real battle sharing ( Keep the process alive )》
《 Wechat team original sharing :Android Version of wechat backstage to keep the real battle sharing ( Network security chapter )》
《 Mobile IM practice : Realization Android Version of wechat's intelligent heartbeat mechanism 》
《 Mobile IM practice :WhatsApp、Line、 Heartbeat strategy analysis of wechat 》
>> More articles of the same kind ……
[4] of WEB End instant messaging development :
《 Novice entry post : In the history of the most complete Web Detailed explanation of the principle of end instant messaging technology 》
《Web End instant messaging technology inventory : Short polling 、Comet、Websocket、SSE》
《SSE Technical details : A brand new HTML5 Server push event technology 》
《Comet Technical details : be based on HTTP Long connection Web End real-time communication technology 》
《WebSocket Detailed explanation ( One ): A preliminary understanding WebSocket technology 》
《socket.io A little practice and thinking of message push 》
>> More articles of the same kind ……
[5] of IM Architecture design :
《 Talking about IM Architecture design of the system 》
《 Brief introduction of mobile terminal IM The pits developed : Architecture design 、 Communication protocol and client 》
《 A set of original distributed instant messaging (IM) System theoretical framework scheme 》
《 From zero to excellence : The evolution process of the technical framework of JD customer service instant messaging system 》
《 Mushroom Street im /IM Architecture selection of server development 》
《 tencent QQ1.4 Technology challenges and architecture evolution of 100 million online users PPT》
《 Wechat technical director talks about architecture : The way of WeChat —— The greatest truths are the simplest ( Speech full text )》
《 How to interpret 《 Wechat technical director talks about architecture : The way of WeChat —— The greatest truths are the simplest 》》
《 Fast fission : Witness the powerful background architecture of wechat 0 To 1 The evolution of ( One )》
《17 Year's practice : Technical methodology of Tencent's massive products 》
>> More articles of the same kind ……
[6] of IM Safe articles :
《 Instant messaging security ( One ): Understand and use... Correctly Android End encryption algorithm 》
《 Instant messaging security ( Two ): The combination encryption algorithm is discussed in IM Application in 》
《 Instant messaging security ( 3、 ... and ): Commonly used encryption and decryption algorithm and communication security 》
《 Instant messaging security ( Four ): The example analysis Android The risk of hard key coding in 》
《 Transport layer security protocol SSL/TLS Of Java Platform implementation and Demo demonstration 》
《 Combining theory with practice : A typical set of IM Communication protocol design details ( Including security layer design )》
《 Wechat new generation communication security solution : be based on TLS1.3 Of MMTLS Detailed explanation 》
《 From Ali OpenIM: Create a safe and reliable instant messaging service technology practice sharing 》
>> More articles of the same kind ……
[7] About real-time audio and video development :
《 Audio and video development of instant messaging ( One ): The theory of video codec 》
《 Audio and video development of instant messaging ( Two ): Digital video introduction of video coding and decoding 》
《 Audio and video development of instant messaging ( 3、 ... and ): Coding basis of video coding and decoding 》
《 Audio and video development of instant messaging ( Four ): Prediction technology of video codec 》
《 Audio and video development of instant messaging ( 5、 ... and ): Understanding the mainstream video coding technology H.264》
《 Audio and video development of instant messaging ( 6、 ... and ): How to start learning audio codec technology 》
《 Audio and video development of instant messaging ( 7、 ... and ): Introduction to audio fundamentals and coding principles 》
《 Audio and video development of instant messaging ( 8、 ... and ): Common real-time voice communication coding standards 》
《 Audio and video development of instant messaging ( Nine ): Echo and echo cancellation of real-time voice communication summary 》
《 Audio and video development of instant messaging ( Ten ): Echo cancellation in real-time voice communication Technical details 》
《 Audio and video development of instant messaging ( 11、 ... and ): Detailed explanation of packet loss compensation technology in real-time voice communication 》
《 Audio and video development of instant messaging ( Twelve ): Discussion on the framework of real-time audio and video chat for multiple people 》
《 Audio and video development of instant messaging ( 13、 ... and ): Real time video coding H.264 Characteristics and advantages of 》
《 Audio and video development of instant messaging ( fourteen ): Real time audio and video data transmission protocol 》
《 Audio and video development of instant messaging ( 15、 ... and ): Chat P2P And real-time audio and video applications 》
《 Audio and video development of instant messaging ( sixteen ): Some suggestions on the development of real-time audio and video in mobile terminal 》
《 Audio and video development of instant messaging ( seventeen ): Video coding H.264、V8 The past and this life 》
《 Open source real-time audio and video technology WebRTC Advantages and disadvantages 》
《 Conscience sharing :WebRTC Zero basic developer tutorial ( chinese )》
>> More articles of the same kind ……
[8] IM Develop comprehensive articles :
《 Mobile IM The technical problems that development needs to face 》
《 Development IM Is it better to use byte stream or character stream to design your own protocol ?》
《 Do you know the mainstream way of voice message chat ?》
《IM How to ensure the reliable delivery of messages in the system ( namely QoS Mechanism )》
《 Talk about mobile IM Optimization of login request in development 》
《 It's completely self-developed IM How to design “ Failure to retry ” Mechanism ?》
《 Technical test and analysis of the influence of wechat on the network ( Paper full text )》
《 The principle of instant messaging system 、 Technology and Application ( Technical papers )》
《 Open source IM engineering “ Mushroom street TeamTalk” The status quo of : An open source show with no end 》
>> More articles of the same kind ……
[9] Open source mobile IM Technical framework information :
《 Open source mobile IM Technical framework MobileIMSDK: Quick start 》
《 Open source mobile IM Technical framework MobileIMSDK: frequently asked questions 》
《 Open source mobile IM Technical framework MobileIMSDK: Stress test report 》
《 Open source mobile IM Technical framework MobileIMSDK:Android edition Demo Use the help 》
《 Open source mobile IM Technical framework MobileIMSDK:Java edition Demo Use the help 》
《 Open source mobile IM Technical framework MobileIMSDK:iOS edition Demo Use the help 》
《 Open source mobile IM Technical framework MobileIMSDK:Android Client development guide 》
《 Open source mobile IM Technical framework MobileIMSDK:Java Client development guide 》
《 Open source mobile IM Technical framework MobileIMSDK:iOS Client development guide 》
《 Open source mobile IM Technical framework MobileIMSDK:Server End development guide 》
>> More articles of the same kind ……
[10] Articles on Push Technology :
《iOS The push service of APNs Detailed explanation : Design thinking 、 Technical principles and defects, etc 》
《Android End message push summary : Realization principle 、 The heartbeat keeps alive 、 Problems encountered, etc 》
《 Literacy stickers : know MQTT Communication protocol 》
《 One is based on MQTT Integrity of communication protocol Android push Demo》
《 Ask for advice android Message push :GCM、XMPP、MQTT The advantages and disadvantages of the three schemes 》
《 Mobile real-time message push technology analysis 》
《 Literacy stickers : Talking about iOS and Android The principle and difference of background real-time message push 》
《 Absolutely dry : be based on Netty Push service technology points to achieve massive access 》
《 Mobile IM practice : Google News push service (GCM) Research ( From wechat )》
《 Why wechat 、QQ In this way IM Tools not used GCM Service push message ?》
>> More articles of the same kind ……
[11] More instant messaging technology good article classification :
http://www.52im.net/forum.php?mod=collection&op=all
author :Jack Jiang ( Click the author name to enter Github)
Source :http://www.52im.net/space-uid-1.html
communication : Welcome to the instant messaging development exchange group 215891622
Discuss :http://www.52im.net/
Jack Jiang At the same time 【 original Java Swing Appearance engineering BeautyEye】 and 【 Lightweight mobile instant messaging framework MobileIMSDK】 The author of , You can go to download and exchange .
边栏推荐
猜你喜欢

2022.2.17

图解OneFlow的学习率调整策略

广和通联合安提国际为基于英伟达 Jetson Xavier NX的AI边缘计算平台带来5G R16强大性能

关于支付接口回调地址参数字段是“notify_url”,签名过后的特殊字符url编码以后再解码后出现错误(¬ , ¢, ¤, £)

Multipass Chinese document - setup driver
![[unity3d] human computer interaction input](/img/4d/47f6d40bb82400fe9c6d624c8892f7.png)
[unity3d] human computer interaction input

Guanghetong and anti international bring 5g R16 powerful performance to the AI edge computing platform based on NVIDIA Jetson Xavier nx

Yolov5 super parameter setting and data enhancement analysis

86. (cesium chapter) cesium overlay surface receiving shadow effect (gltf model)

Pycharm package import error without warning
随机推荐
pycharm 导包错误没有警告
2022.2.13
Hash problem
Collections and dictionaries
YOLOv5-6.0的一些参数设置和特征图可视化
微信小程序保存图片的方法
2022.2.15
Codeforces Round #800 (Div. 2)
Using requests library and re library to crawl web pages
【Unity3D】碰撞体组件Collider
File upload and security dog
Sentimentin tensorflow_ analysis_ cell
Rsync common error messages (common errors on the window)
超高精度定位系统中的UWB是什么
Why do many Shopify independent station sellers use chat robots? Read industry secrets in one minute!
The beautiful scenery is natural, and the wonderful pen is obtained by chance -- how is the "wonderful pen" refined?
Wechat applet exits the applet (navigator and api--wx.exitminiprogram)
Large numbers (C language)
MySql如何删除所有多余的重复数据
Use to_ Numeric to numeric type