Reputation: 14869
I have a C/C++ application for a TCP client and server in Linux.
Suppose that after the TCP connection is in place, neither the server nor the client sends any data at all for huge amount of time. They do not even send any heartbeat each other.
By TCP protocol, how long the connectivity is supposed to be in place?
Does the connection drop due to inactivity?
If so is there any socket option where I can specify or define any kind of timeout behaviour?
Upvotes: 4
Views: 4906
Reputation: 148870
I am afraid that the only sensible answer should be it depends.
A TCP connection can use a number of intermediary relays between both ends. Each component (read each end and each relay) can have its own strategy for closing inactive connections.
A common workaround is to use keepalive as an optional TCP feature. It consists of empty packets sent by one end when the connection is idle for more than a defined timeout. The peer should answer with an ACK, even if it does not support the keepalive extension, which is enough to maintain the connection active at the TCP level.
In Linux for example, keepalive can be set at kernel level, and will be active for all new TCP connections. It may be a bad idea because keepalive is off by default to avoid ovehead on network. From the referenced page:
The procedures involving keepalive use three user-driven variables:
tcp_keepalive_time
the interval between the last data packet sent (simple ACKs are not considered data) and the first keepalive probe; after the connection is marked to need keepalive, this counter is not used any further tcp_keepalive_intvl
the interval between subsequential keepalive probes, regardless of what the connection has exchanged in the meantime
tcp_keepalive_probes
the number of unacknowledged probes to send before considering the connection dead and notifying the application layer
They can be set for example with sysctl(8)
:
# sysctl -w \ > net.ipv4.tcp_keepalive_time=600 \ > net.ipv4.tcp_keepalive_intvl=60 \ > net.ipv4.tcp_keepalive_probes=20 net.ipv4.tcp_keepalive_time = 600 net.ipv4.tcp_keepalive_intvl = 60 net.ipv4.tcp_keepalive_probes = 20
It is also possible to set it only for some connections at the application level with setsockopt
:
/* Set the option active */ int optval = 1; socklen_t optlen = sizeof(optval); if(setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen) < 0) { perror("setsockopt()"); close(s); exit(EXIT_FAILURE); }
Upvotes: 4
Reputation: 310860
By TCP protocol, how long the connectivity is supposed to be in place?
Forever.
Does the connection drop due to inactivity?
No.
If so is there any socket option where I can specify or define any kind of timeout behaviour?
There is SO_RCVTIMEO, where supported. This provides a read timeout for the recv()
method and friends.
Upvotes: 2