Tuesday, November 30, 2010

Linux TCP keepalive property view

TCP is a connection-oriented, in practice often need to test whether the connection is also available if not available, can be divided into: a. connections on duanzhengchang close .b. connections on the side of a non-graceful shutdown, this includes on-device power-down, a program crash, the network is interrupted, and so this is no longer notice-to-end, so the connection is persistent, waste of national resources .tcp protocol stack has a keepalive property, you can proactively detect socket is available, however this property is the default value is very large. global settings you can change the/etc/sysctl.conf, plus: net.ipv4.tcp_keepalive_intvl = 20net.ipv4.tcp_keepalive_probes = 3net.ipv4.tcp_keepalive_time = 60 in the program settings are as follows: # include # include # include # include # includeintkeepAlive = 1;//open the keepalive property intkeepIdle = 60;//if the connected in 60 seconds with no data exchanges, for detecting intkeepInterval = 5;//when the contract of detection interval is 5 seconds intkeepCount = 3;//number of attempts to detect if the 1st detection package will receive a response, then after 2 times lose fat .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 performance is detected when the tcp socket to the client is no longer available (not detecting packet, or the exploration package did not receive ACK response packet), the select returns the socket is readable, and recv returns-1 when, at the same time reset errno as ETIMEDOUT on.

No comments:

Post a Comment