TCP connection status explanation and troubleshooting

Source: Internet
Author: User

TCP connection status explanation and troubleshooting

By understanding the status of TCP, We Can troubleshoot and locate network or system faults. (Summarize the content on the Network)

1. TCP status

LISTENING: listens for connection requests from remote TCP ports.First, the server needs to open a socket for listening, and the status is LISTEN. A service is provided in the LISTENING status. a tcp status change is the status change of a port. When a service is provided, a port is opened. For example, the www service is enabled on port 80 by default, the default port for providing the ftp service is 21. When the provided service is not connected, it is in the LISTENING status. After the FTP service is started, it is in the LISTENING status. When the listener is in the LISTENING status, the port is open, waiting for connection, but not yet connected. Just as the door of your house has been opened, but no one has come in.
To check the LISTENING status, the most important thing is to check which ports are enabled on the local machine and which program these ports are enabled. Closing unnecessary ports is a very important aspect to ensure security, the Service port corresponds to a service (Application). If you stop the service, the port is closed. For example, to disable port 21, you only need to stop the FTP service in the IIS service. For more information, see other articles.
If you are unfortunately in the service Port Trojan, the trojan also opens a port in the LISTENING status.

SYN-SENT: client SYN_SENT status:After sending the connection request again, wait for the matching connection request: the client calls connect through the application to perform active open. therefore, the client tcp sends a SYN request to establish a connection. then the status is set to SYN_SENT. /* The socket is actively attempting to establish a connection. wait for the matched connection request after sending the Connection Request */
When a request is sent to a connection, the client first sends a synchronous signal to the machine to be accessed. The status is SYN_SENT. If the connection is successful, the status changes to ESTABLISHED. Under normal circumstances, the SYN_SENT status is very short. For example, to access the website http://www.baidu.com, if it is a normal connection, use TCPView to observe the connection ESTABLISHED by IEXPLORE. EXE (IE) will find that soon from SYN_SENT to ESTABLISHED, indicating the connection is successful. SYN_SENT may not be in a fast state.
If many SYN_SENT instances are found, there are usually several situations: first, the website you want to visit does not exist or the line is not good, and second, scanning a machine with a network segment using Scan software, there will also be many SYN_SENT, and the virus may be involved. For example, if the "Shock Wave" is in progress, other machines will be scanned during the virus attack, so many SYN_SENT will appear.

SYN-RECEIVED: the server state SYN_RCVD again receives and sends a connection request and waits for the other party to confirm the connection request when the server receives the synchronous signal sent by the client, send the flag ACK and SYN 1 to the client, and the server is in the SYN_RCVD status. If the connection is successful, the status changes to ESTABLISHED. Under normal circumstances, the SYN_RCVD status is very short.
If many SYN_RCVD states are found, your machine may be attacked by SYN Flood DoS attacks. SYN Flood attack principle is: when three handshakes are performed, the attack software sends a SYN connection request to the attacked server (the first step of the handshake), but this address is forged, for example, the attack software randomly spoofs addresses such as 51.133.163.104 and 65.158.99.152. When the server receives the connection request, it sends the flag ACK and SYN to the client (step 2 of handshake). However, the IP addresses of these clients are forged and the server cannot find the client, that is to say, the third step of the handshake cannot be completed. In this case, the server will generally retry (re-send SYN + ACK to the client) and wait for a while before discarding the unfinished connection. The length of this time is called SYN Timeout, generally, this time is an order of magnitude of minutes (about 30 seconds-2 minutes). A user exception causes a server thread to wait for 1 minute, which is not a big problem, however, if a malicious attacker simulates this situation in large numbers, the server will consume a lot of resources to maintain a very large semi-connection list-tens of thousands of semi-connections, even simply saving and traversing will consume a lot of CPU time and memory, not to mention constantly retrying the IP addresses in this list with SYN + ACK. In this case, from the perspective of a normal customer, the server loses response. In this case, we call it: The server is under SYN Flood attack (SYN Flood attack))

ESTABLISHED: indicates an open connection.The state of ESTABLISHED indicates that the two machines are transmitting data. The most important thing to observe is to see which program is in the state of ESTABLISHED.
The server has many ESTABLISHED statuses: netstat-nat | grep 9502 or lsof-I: 9502. When the client is not actively closed, the connection is closed: the FIN sent by the client is lost or not sent.

At this time, if the FIN package is sent when the client is disconnected, the server will be in the CLOSE_WAIT status;

At this time, if the FIN package is not sent when the client is disconnected, the server will still display the ESTABLISHED status;

Result The client reconnects to the server.

The newly connected client (that is, the disconnected client is re-connected) must be ESTABLISHED on the server. If the client repeats this situation, then, the server will have a lot of fake ESTABLISHED connections and CLOSE_WAIT connections.

The final result is that other new clients cannot be connected. However, with netstat, you can still see that a connection has been ESTABLISHED and ESTABLISHED is displayed, but you cannot enter the program code.

FIN-WAIT-1:Wait for the remote TCP connection interruption request, or the previous connection interruption request confirmation actively closes (active close) end application calls close, so TCP sends a FIN request to actively close the connection, and then enters the FIN_WAIT1 status. /* The socket is closed, and the connection is shutting down. wait for the confirmation of the remote TCP connection interruption request or the previous connection interruption request */

FIN-WAIT-2: Waiting for connection interruption requests from remote TCPAfter receiving the ACK, the client enters FIN-WAIT-2. /* Connection is closed, and the socket is waiting for a shutdown from the remote end. from Remote TCP waiting for connection interruption request */This is the well-known semi-closed status, which is the status after the client and server shake hands when the connection is closed. In this state, the application can accept data, but data cannot be sent. However, the client is always in the FIN_WAIT_2 state, and the server is always in the WAIT_CLOSE state, the Application Layer determines to close this state.
CLOSE-WAIT: Waiting for connection interruption requests from Local UsersPassive close (passive close) after TCP receives the FIN, it sends an ACK to respond to the FIN request (its receipt is also passed to the upper-layer application as the file Terminator) and enters CLOSE_WAIT. /* The remote end has shut down, waiting for the socket to close. waiting for a connection interruption request from a local user */

CLOSING: waiting for confirmation of remote TCP connection interruptionRare./* Both sockets are shut down but we still don't have all our data sent. Wait for remote TCP to confirm the connection interruption */

LAST-ACK: waiting for confirmation of the original connection interruption request sent to remote TCPAfter a period of time, the application that receives the file Terminator will call CLOSE to CLOSE the connection. As a result, TCP also sends a FIN, waiting for the ACK of the other party. the LAST-ACK. /* The remote end has shut down, and the socket is closed. waiting for acknowledgement. wait for confirmation of the original connection interruption request sent to remote TCP */

TIME-WAIT: WAIT for enough TIME to confirm that the remote TCP receives the connection interruption request.After the active shutdown side receives the FIN, TCP sends the ACK packet and enters the TIME-WAIT Status. /* The socket is waiting after close to handle packets still in the network. wait for enough time to ensure that the remote TCP receives the confirmation of the connection interruption request */TIME_WAIT Wait Status, which is also called 2MSL status, after TIME_WAIT2 sends the last ACK datagram, it enters the TIME_WAIT status, this status prevents the datagram of the last handshake from being transmitted to the other party and prepared (note that this is not the four handshakes, but the fourth handshake is the insurance status ). This State ensures that both parties can end normally, but the problem also arises.
Because of the 2MSL status of the plug-in port (the plug-in Port indicates the IP address and port pair, socket), the application cannot use the same plug-in again in 2MSL time, which is better for the customer program, however, for a service program, such as httpd, it always needs to use the same port for service. In 2MSL time, an error occurs when httpd is started (the plug is used ). In order to avoid this error, the server provides a concept of Calm time, which means that although the server can be restarted in 2MSL time, however, this server still needs to wait for the 2MSL time to complete the next connection. For details, see: TIME_WAIT error caused by Cannot assign requested address

CLOSED: No connection statusThe passive shutdown end enters the closed state after receiving the ACK package. Connection ended./* The socket is not being used. No connection status */

2. TCP status migration Roadmap

The two routes of the client and server describe the roadmap of TCP status migration:

This is a complex state migration diagram, because it contains two parts: Server State migration and client state migration. If you look at this diagram from a certain perspective, it will be much clearer. The server and client here are not absolute. The client sends the data, and the server receives the data. Client application status migration DiagramThe client status can be expressed in the following process: CLOSED-> SYN_SENT-> ESTABLISHED-> FIN_WAIT_1-> FIN_WAIT_2-> TIME_WAIT-> the CLOSED process is the process that should be performed when the program is normal, as shown in the diagram in the book, when a connection is established, when the client receives the ACK of the SYN packet, the client opens an interactive data connection. The client ends the connection actively. After the client ends the application, it needs to go through the FIN_WAIT_1, FIN_WAIT_2, and other statuses. The migration of these statuses is the four handshakes mentioned above to end the connection.
Server Status migration DiagramThe server status can be represented by the following process: CLOSED-> LISTEN-> SYN received-> ESTABLISHED-> CLOSE_WAIT-> LAST_ACK-> CLOSED when establishing a connection, the server enters the data interaction status only after the third handshake, while closing the connection is after the second handshake (not the fourth ). After the feature is disabled, you must wait for the client to provide the final ACK package before entering the initial state.
Other status migrationThere are also some other State migration. These State migration targets the server and the client, which are summarized as follows: LISTEN-> SYN_SENT. This is a simple explanation, and the server sometimes needs to open the connection. SYN_SENT-> SYN received. If the server and client receive SYN datagram in the SYN_SENT state, they both need to send the syn ack datagram and adjust their status to the SYN received state, prepare to enter ESTABLISHED SYN_SENT-> CLOSED. When sending times out, it will return to the CLOSED status. SYN _ received-> LISTEN. If an RST packet is received, it returns to the LISTEN status. SYN _ received-> FIN_WAIT_1. This migration means that you can directly jump to the FIN_WAIT_1 status and wait to close without going to the ESTABLISHED status.


How can I keep this image in my mind? Then, you must have a deep understanding of every state of the image and the conversion process. You cannot just stay in the dark. Next, we will analyze the 11 statuses of this image in detail to enhance the memory! However, let's review the three-way handshake process of TCP connection establishment and the four-way handshake process of closing the connection.

3. Three handshakes are established for TCP connections.

TCP is a connection-oriented protocol. Therefore, a connection must be established before both parties send data. Client Connection Server:

When the Client calls the socket function, the Client generates a socket in the Closed state.
(1) first handshake: the Client calls the connect function again, and the system randomly assigns a port to the Client, together with the parameters (the IP address and port of the Server) in connect ), this forms a connection triplet. The client sends a TCP packet with the SYN sign to the server. This is packet 1 during the three-way handshake. Connect call puts the Client socket inSYN_SENTStatus, waiting for confirmation from the server; SYN: Synchronous Sequence number (Synchronize Sequence Numbers ).

(2)Second handshake:When the server receives the syn packet, it must confirm the customer's SYN (ack = j + 1) and send a SYN Packet (syn = k), that is, the SYN + ACK packet.SYN_RECVStatus;

(3) third handshake:The client receives the server SYN + ACK package and sends the ACK (ack = k + 1) Confirmation package to the server. After the package is sent, the client and the server enterESTABLISHEDStatus, complete three handshakes. The connection can be read and written.

A complete three-way handshake is request-response-re-confirmation.

The TCP protocol establishes a connection through three packet segments. This process is called the three-way handshake, as shown in. Corresponding function interfaces:


2) Server
When the Server calls the socket function, the Server generates a Closed listener socket.
The Server calls the bind operation, associates the listening socket with the specified address and port, and then calls the listen function. The system allocates unfinished queues and completes queues for the socket, at this time, the listening socket can accept the connection from the Client, and the listening socket is in the LISTEN status.
When the Server calls the accept operation, a completed client connection is retrieved from the Completion queue, and a session socket is generated between the server and the client socket, the status of this session socket is ESTABLISH.

It can be seen that when the client calls connect, the connection request is triggered and the syn j packet is sent to the server. Then, connect is blocked. When the server listens to the connection request, it receives the syn j packet, call the accept function to receive requests and send syn k, ack j + 1 to the client. Then, accept is blocked. After the client receives the syn k and ack j + 1 from the server, connect returns, then, confirm the syn k. When the server receives the ack k + 1, accept returns. The three handshakes are completed and the connection is established.
We can view the specific process through network packet capture: for example, our server enables port 9502. Use tcpdump to capture packets: Tcpdump-iany tcp port 9502Then we use telnet 127.0.0.1 9502 to open the connection.: telnet 127.0.0.1 9502 14:12:45. 104687 IP localhost.39870> localhost.9502: Flags [S], seq 2927179378, win 32792, options [mss 16396, sackOK, TS val 255474104 ecr 0, nop, wscale 3], length 0 (1)
14:12:45. 104701 IP localhost.9502> localhost.39870: Flags [S.], seq 1721825043, ack 2927179379, win 32768, options [mss 16396, sackOK, TS val 255474104 ecr 255474104, nop, wscale 3], length 0 (2)
14:12:45. 104711 IP localhost.39870> localhost.9502: Flags [.], ack 1, win 4099, options [nop, nop, TS val 255474104 ecr 255474104], length 0 (3)
14:13:01. 415407 IP localhost.39870> localhost.9502: Flags [P.], seq, ack 1, win 4099, options [nop, nop, TS val 255478182 ecr 255474104], length 7
14:13:01. 415432 IP localhost.9502> localhost.39870: Flags [.], ack 8, win 4096, options [nop, nop, TS val 255478182 ecr 255478182], length 0
14:13:01. 415747 IP localhost.9502> localhost.39870: Flags [P.], seq, ack 8, win 4096, options [nop, nop, TS val 255478182 ecr 255478182], length 18
14:13:01. 415757 IP localhost.39870> localhost.9502: Flags [.], ack 19, win 4097, options [nop, nop, TS val 255478182 ecr 255478182], length 0

We can see that (1)(2)(3) three steps are to establish tcp: First handshake:14:12:45. 104687 IP localhost.39870> localhost.9502: Flags [S], seq 2927179378 Client IP localhost.39870 (the client port is generally automatically allocated) Send a syn Packet (syn = j) to the server localhost.9502) to the server, syn seq = 2927179378
The second handshake:
14:12:45. 104701 IP localhost.9502> localhost.39870: Flags [S.], seq 1721825043, ack 2927179379, the server receives the syn packet, you must confirm the customer's SYN (ack = j + 1), and also send a SYN Packet (syn = k ), that is, SYN + ACK packets
SYN (ack = j + 1) = ack 2927179379 server host SYN Packet (syn = seq 1721825043)

The third handshake:14:12:45. 104711 IP localhost.39870> localhost.9502: Flags [.], ack 1,
The client receives the server's SYN + ACK package and sends the ACK (ack = k + 1) Confirmation package to the server. After the client and server enter the ESTABLISHED status, they can communicate with each other. At this time, it has nothing to do with the accept interface. Even if there is no accepte, three handshakes are completed. The connection fails. Generally, the network is faulty, the network is overloaded, or the number of connections is full. Purple Background: IP localhost.39870> localhost.9502: Flags [P.], seq, ack 1, win 4099, options [nop, nop, TS val 255478182 ecr 255474104], length 7
The client sends 7 bytes of data to the server,
IP localhost.9502> localhost.39870: Flags [.], ack 8, win 4096, options [nop, nop, TS val 255478182 ecr 255478182], length 0
The server confirms to the customer that the data has been received
IP localhost.9502> localhost.39870: Flags [P.], seq, ack 8, win 4096, options [nop, nop, TS val 255478182 ecr 255478182], length 18
The server then writes data to the client at the same time.
IP localhost.39870> localhost.9502: Flags [.], ack 19, win 4097, options [nop, nop, TS val 255478182 ecr 255478182], length 0
The client confirms to the server that the data has been received
This is a reliable tcp connection. Each communication requires confirmation from the other party.

4. Termination of TCP connection (four handshakes are released)

Because the TCP connection is full-duplex, each direction must be closed separately. This principle is that when one party completes its data sending task, it can send a FIN to terminate the connection in this direction. Receiving a FIN only means that there is no data flow between the two parties. a tcp connection can still send data after receiving a FIN. First, the party that closes the service will take the initiative to close the service, and the other party will passively close the service.

Three handshakes are required to establish a connection, and four handshakes are required to terminate a connection. This is caused by the semi-close of TCP,

(1) Client A sends a fin to disable data transmission from client A to server B (packet segment 4 ).

(2) When server B receives the FIN, it sends back an ACK and confirms that the serial number is 1 (packet segment 5 ). Like SYN, a FIN occupies a sequence number.

(3) server B Closes the connection with client A and sends A FIN to Client A (packet segment 6 ).

(4) Client A sends back the ACK message for confirmation, and sets the confirmation sequence number to receive the serial number plus 1 (packet segment 7 ).

Corresponding function interface

The call process is as follows:

  • 1) when the client wants to close the connection between the client and the server. The client (an application process) first calls close to close the connection, and TCP sends a fin m; the client is inFIN_WAIT1Status.
  • 2) When the server receives the fin m, it is passively disabled. Confirm the FIN and return it to the client ACK. After the server returns the ACK to the client, the client isFIN_WAIT2Status, the server is inCLOSE_WAITStatus. Its receipt is also passed to the application process as a file Terminator, because the receiving of FIN means that the application process can no longer receive additional data on the corresponding connection;
  • 3) after a period of time, when the server detects the close operation on the client side (read returns 0 ). The server that receives the file Terminator calls close to close its socket. This causes TCP on the server to send a fin n; the server status isLAST_ACK.
  • 4) when the client receives the FIN from the server. The client socket is inTIME_WAITStatus, it sends an ack confirmation to the server. After the server receives the ack confirmation, the socket is in the CLOSED status.

    In this way, there is a FIN and ACK in each direction.

    1. Why is the three-way handshake while the four-way handshake when the connection is closed?

    This is because the SOCKET in the LISTEN status of the server can respond to ACK and SYN after receiving the SYN Packet connection request) it is sent in a message. However, when the connection is closed, when the other party receives the FIN Message notification, it only indicates that the other party has no data to send to you; but not all your data may have been sent to the other party, therefore, you may not close the SOCKET immediately, that is, you may need to send some data to the other party, and then send the FIN message to the other party to indicate that you agree to close the connection now, therefore, the ACK messages and FIN messages are sent separately in most cases.

    2. Why does the TIME_WAIT status still need to be 2 MSL before it can be returned to the CLOSED status?

    This is because, although both parties agree to close the connection, and the four messages of the handshake are also coordinated and sent, it is reasonable to directly return to the CLOSED status (like from SYN_SEND to ESTABLISH):

    On the one hand, the end of TCP full-duplex connection is reliably implemented, that is, when the last ACK is lost, the passive shutdown end resends the FIN. Therefore, the active shutdown end must maintain the status information, to allow it to resend the final ACK.

    On the other hand, because we must assume that the network is not reliable, you cannot guarantee that the last ACK message you sent will be received by the other party, therefore, the SOCKET in the LAST_ACK status may not receive the ACK message because of timeout, but resend the FIN message. Therefore, the TIME_WAIT status is used to resend the possibly lost ACK message.

    During the 2MSL wait period, TCP defines that the connection (4 tuples) cannot be used any more, and any late packets will be discarded. Imagine that without the limit of 2 MSL, the new connection exactly meets the original 4 tuples. At this time, the connection may receive the delayed packets on the network and may interfere with the newly established connection.

    5. Open both

    It is possible for two applications to execute active opening at the same time, although it is less likely to happen. Each end sends a SYN to the other end, and each end uses the port known to the end as the local port. For example:

    An application in host a uses port 7777 as the local port and connects to port 8888 of host B for active access.

    An application in host B uses port 8888 as the local port and connects to host a port 7777 for active access.

    In this case, only one connection is opened.

    This connection requires four data exchanges, while a typical connection requires only three exchanges (that is, three handshakes)

    However, most Berkeley TCP/IP implementations do not support simultaneous enabling.

    6. disable both

    If the application sends FIN at the same time, the FIN_WAIT_1 status will first be entered after sending. After receiving the FIN from the peer end, an ACK will be returned, which will enter the CLOSING status. After receiving the ACK from the peer end, it enters the TIME_WAIT status. This situation is called "Disable at the same time.

    At the same time, there are also four packet exchanges required for disabling, which is the same as the typical disabling.


    7. The server handles unexpected client disconnection in TCP Communication

    Reference address: http://blog.csdn.net/kkkkkxiaofei/article/details/12966407

    If the TCP connection is normally closed by the other party, that is, if the other party correctly calls closesocket (s) or shutdown (s), the preceding Recv or Send call will return immediately, and an error is reported. This is because the close socket (s) or shutdown (s) has a normal closing process and will tell the other party that "the TCP connection has been closed and you do not need to send or accept the message ".

    However, the client (a 3G mobile device) does not close the socket normally if it is accidentally disconnected. The two sides did not follow the four waves in the Agreement to disconnect the connection.

    At this time, the party that is executing the Recv or Send operation will wait because there is no notification of connection interruption, that is, it will be stuck for a long time.

    For example, if one party has closed or terminated the connection abnormally, but the other party does not know, we call this TCP connection semi-open.

    The active mechanism is used to solve unexpected interruptions. In addition, the alive mechanism allows the underlying implementation to be implemented by itself.

    1. Write your own heartbeat package program

    Simply put, add a thread to your program and regularly send data packets to the peer end to check whether there is an ACK. If yes, the connection is normal. If no, the connection is closed.

    2. Start the keepAlive mechanism in TCP programming.

    I. Both parties propose HEARTBEAT (self-implemented)

    Generally, the client sends a heartbeat packet, and the server does not respond to the heartbeat packet. It only periodically polls to determine whether the interval from the previous time has timed out (the timeout value is set by itself ). The server does not want to increase the server's traffic and reduce the pressure.

    However, there are three scenarios:

    Case 1.

    The client sends a heartbeat packet after a long time due to some network delay (it has not been disconnected). If the server uses the timeout value set by itself, it determines that it has been disconnected and then closes the socket. If the client has a reconnection mechanism, the client will reconnect. If you are not sure whether the client is shut down in this way, you must select send when ShutDown, which means that the sending channel is closed, and the server can also receive it, what if the client is sending important data?

    Case 2.

    The client has not passed the heartbeat for a long time, but it is indeed disconnected. Before the restart, the server determines that it has timed out and actively closes the interface. Then, it successfully interacts with each other four times.

    Case 3.

    The client has not passed the heartbeat for a long time, but it is indeed disconnected. Before the restart, the server's polling has not yet determined its timeout, and the client has reconnected when the client is not actively closed.

    At this time, if the FIN package is sent when the client is disconnected, the server will be in the CLOSE_WAIT status;

    At this time, if the FIN package is not sent when the client is disconnected, the server will still display the ESTABLISHED status;

    The newly connected client (that is, the disconnected client is re-connected) must be ESTABLISHED on the server. At this time, there is a problem, if the previous old connection has not been detected through polling (this is normal, timer always has an interval), and at this time, the client repeats the stage 3, then, the server will have a lot of fake ESTABLISHED connections and CLOSE_WAIT connections.

    The final result is that other new clients cannot be connected. However, with netstat, you can still see that a connection has been ESTABLISHED and ESTABLISHED is displayed, but you cannot enter the program code. I initially felt that this was caused by a false ESTABLISHED connection and CLOSE_WAIT connection that would occupy a large amount of system resources, the program cannot create a connection again (because every time I find this problem, I only connect about 10 clients, but there are more than 40 invalid connections ). In recent days, the test showed that there were only two or three devices connected to the program, but there were eight or so virtual connections, and the new client was no longer connected. At this time, I thought I was wrong. It is impossible for these connections to occupy a large number of connections. If we say there are still several dozen connections. However, it is certain that the device is constantly restarting, and the server side is simple round robin, which cannot be processed in time and cannot be solved yet.

    Ii. Use KeepAlive

    In fact, the principle of keepalive is a heartbeat packet embedded in TCP,

    Take the server as an example. If the current server detects no data transmission for more than a certain period of time (7,200,000 milliseconds by default, that is, 2 hours, then a keep-alive packet (the keep-alive packet is a combination of ACK and current TCP serial number minus one) will be sent to the client. In this case, the client should be one of the following three cases:

    1. The client still exists and the network connection is in good condition. The client returns an ACK. The server resets the timer (reset the survival timer) After receiving the ACK and sends the probe after 2 hours. If data is transmitted over the connection within two hours, the delay is extended by two hours.

    2. The client is shut down abnormally or the network is disconnected. In both cases, the client does not respond. The server does not receive a probe response to it, and repeat keep-alive packet after a certain period of time (the system defaults to 1000 MS, in addition, the message is repeatedly sent for a certain number of times (the default value is 5 in 2000 XP 2003, and the default value is 10 in Vista ).

    3. The client has crashed but has been restarted. In this case, the server will receive a response to its survival detection, but the response is a reset, causing the server to terminate the connection.

    2 hours of free time is too long for applications. Therefore, we need to manually enable the Keepalive function and set reasonable Keepalive parameters.

    The global settings can be changed to/etc/sysctl. conf, plus:
    Net. ipv4.tcp _ keepalive_intvl = 20
    Net. ipv4.tcp _ keepalive_probes = 3
    Net. ipv4.tcp _ keepalive_time = 60

    Set in the program as follows:

     

    # Include <sys/socket. h> # include <netinet/in. h> # include <arpa/inet. h> # include <sys/types. h> # include <netinet/tcp. h> int keepAlive = 1; // enable the keepalive attribute int keepIdle = 60; // if the connection has no data exchange within 60 seconds, the int keepInterval = 5 will be detected; // The packet sending time interval is 5 seconds int keepCount = 3; // Number of probe attempts. if the response is received for 1st times, the next two times will not be sent again. setsockopt (rs, SOL_SOCKET, SO_KEEPALIVE, (void *) & keepAlive, sizeof (keepAlive); setsockopt (rs, SOL_TCP, TCP_KEEPIDLE, (void *) & keepIdle, sizeof (keepIdle); setsockopt (rs, SOL_TCP, TCP_KEEPINTVL, (void *) & keepInterval, sizeof (keepInterval); setsockopt (rs, SOL_TCP, TCP_KEEPCNT, (void *) & keepCount, sizeof (keepCount ));

    In the program, when tcp detects that the Peer socket is no longer available (the detection package cannot be issued, or the detection package does not receive the ACK response package), select returns the socket readable, in addition,-1 is returned for recv and errno is set to ETIMEDOUT.

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.