How to gracefully close a socket

Source: Internet
Author: User

Recently, in windows programming, we need to consider "How to gracefully close a socket" and read some information. Now we will compile the relevant information, hoping to help later users (relatively lazy, therefore, the English documents are not translated :-))

1. What did I do when I close the Socket?

Active closure and Passive closure can be used to disable a socket. The former refers to the active shutdown initiated by the local host, while the latter refers to the response made by the local host after detecting that the remote host is closed, thus closing the entire connection.
Shows the status chart:

At first, each socket is in the CLOSED state. When the client initiates a connection, it sends a SYN packet to the server and the client enters the SYN_SENT state.
The server receives the SYN Packet and returns a SYN-ACK packet. After receiving the packet, the client returns an ACK packet. The client changes to the ESTABLISHED State. If the SYN-ACK packet is not received for a long time, the client times out and enters the CLOSED state.
When the server binds and listens to a port, the socket status is LISTEN. When the client attempts to establish a connection, the server receives a SYN Packet and returns the SYN-ACK packet. The server status changes to SYN_RCVD. When the client sends an ACK packet, the server socket status changes to ESTABLISHED.

When a program is in the ESTABLISHED State, there are two ways to close it: active and passive. If you want to disable it, send a FIN package. When your program closesocket or shutdown (Mark), your program sends a FIN packet to the peer, and your socket changes to the FIN_WAIT_1 state. Peer reports an ACK packet and your socket enters the FIN_WAIT_2 state. If the peer is also shutting down the connection, it will send a FIN package to your computer. You feed back an ACK package and convert it to the TIME_WAIT status.
TIME_WAIT status and 2MSL wait status. MSL indicates the Maximum Segment Life Cycle (Maximum Segment life time) indicates the time when a packet exists between the network and when it is discarded. Each IP packet has a TTL (time_to_live). When it is reduced to 0, the packet is discarded. Each vro reduces the TTL value by one and transmits the packet. When a program enters the TIME_WAIT state, it has two MSL times. This allows TCP to resend the last ACK. In case the last ACK is lost, the FIN is re-transmitted. After 2MSL waits for completion, the socket enters the CLOSED state.
Passive close: when the program receives a FIN packet from the peer and returns an ACK packet, the socket of the program is transferred to the CLOSE_WAIT status. Because the peer has been disabled, no messages can be sent. But the program can. To close the connection, the program has been sent to its own FIN to change the TCP socket state of the program to the LAST_ACK state. When the program receives the ACK packet from the peer, the program enters the CLOSED state.

2. Related functions in Winsock2 API

Check MSDN first and see the relevant functions in winsocks2 API: closesocket, shutdown, WSASendDisconnect. Let me give you a general idea. Please check MSDN for details.

Int Closesocket ( SOCKET S)Is used to close the specified socket and recycle all its resources.
Int Shutdown ( SOCKET S,Int How)It is forbidden to prohibit operations specified by how on the specified socket s, but not to recycle resources. After shutdown, s cannot connect or WSAConnect again before closesocket.
Int WSASendDisconnect ( SOCKET S,LPWSABUF LpOutboundDisconnectData)Similar to shutdown, the difference is that the WSASendDisconnect function has an additionalLpOutboundDisconnectDataParameter, which allows sending disconnect data ). however, "The native implementation of TCP/IP on Windows does not support disconnect data. ", so we generally use the shutdown function.

3. Elegant Socket Closure

In MSDN, the Remarks section of the shutdown function contains the following section, which shows how to disable an elegant slcket:

To assure that all data is sent and stored ed on a connected socket before it is closed, an application shoshould useShutdownTo close connection before callingClosesocket. For example, to initiate a graceful disconnect:

 

  1. CallWSAAsyncSelectTo register for FD_CLOSE notification.
  2. CallShutdownWithHow= SD_SEND.
  3. When FD_CLOSE received, callRecvUntil zero returned, or SOCKET_ERROR.
  4. CallClosesocket.

The behavior of closesocket varies with the parameters in setsockopt (). The main impact of closesocket behavior is the linger structure.

If SO_DONTLINGER is true, the SO_LINGER option is disabled.
SO_LINGER delay disconnection struct linger
The preceding two options affect the close action.
Option interval close mode waiting for closing or not
SO_DONTLINGER does not care about elegance or not
SO_LINGER: Zero-force no
SO_LINGER non-zero elegance is
If SO_LINGER is set (that is, the l_onoff field in the linger structure is set to non-zero) and the zero timeout interval is set, closesocket () is executed immediately without being blocked, no matter whether there is queue data not sent or not confirmed. This method is called "forced" or "invalid", because the virtual circuit of the Set interface is reset immediately and unsent data is lost. A wsaeconnreset error occurs when remote recv () is called.
If SO_LINGER is set and a non-zero timeout interval is determined, closesocket () calls the blocking process until all data has been sent or timed out. This type of closure is called an "elegant" closure. Note that if the set interface is set to non-blocking and SO_LINGER is set to a non-zero timeout value, closesocket () will return a WSAEWOULDBLOCK error.
If SO_DONTLINGER is set on a stream class interface (that is to say, the l_onoff field of the linger structure is set to zero), The closesocket () call will return immediately. However, if possible, the queued data will be sent before the set interface is closed. Note that in this case, the implementation of WINDOWS interface sets will retain the interface sets and other resources for a period of uncertain time, which will affect the applications that want to use the interface.

Therefore, you should not set the linger to SO_LINGER and set the timeout to 0. In this case, when the local host calls closesocket, it will cause a "forced" or "invalid" non-elegant shutdown. You can set it to the other two cases based on the actual situation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.