Question: How long can an idle TCP connection remain open?

Answer: According to the standard, indefinitely, however, most implementations impose a connection timeout.

TCP keepalive is a feature that isn’t defined in the TCP specification, as crazy as that might sound. RFC1122 under section mentions keepalives instead.

Excerpt from RFC1122  TCP Keep-Alives

    Implementors MAY include "keep-alives" in their TCP
    implementations, although this practice is not universally
    accepted.  If keep-alives are included, the application MUST
    be able to turn them on or off for each TCP connection, and
    they MUST default to off.

Question: Why do we have TCP keepalives then?

Answer: Servers were the first to have TCP keepalive implemented in their stack. It was useful when a client drops off without closing the connection; keepalives prevent the server from maintaining this half-open connection indefinitely. Without this, the server would eventually experience resource exhaustion and prevent new clients from making connections.

The same could happen to clients, but it’s less of a concern. Because of this, many implementations started imposing connection timeouts when the connection is idle. Windows, for instance, closes a TCP connection after two hours of inactivity (no data being sent). Stateful firewalls (devices performing NAT) also maintain a TCP connection table with timeouts often in the range of 15 minutes. If the timeout is reached, the stateful device removes the connection information from its connection table, and the next time a transmission occurs, it will fail to be received. Most stateful devices would also reply on behalf of the server with a segment with the TCP RESET flag set, informing the sender the connection is no longer valid. The connection must be re-established with a new three-way handshake to continue.

To prevent these issues, some implementations utilize keepalives, which is essentially an empty segment that gets sent to keep the connection active. The keepalive segment has the same sequence number that was used in the previously sent segment. Because the receiver has already seen this sequnce number, it responds with an ACK.

Application Layer Keepalive

Sometimes keepalive is implemented in the application layer. An application developer may know his product will experience fewer issues if there’s a periodic keepalive sent to the application server. And because of this, they may choose to implement keepalive by sending an empty message. Putty is one example of where this feature can be useful.

Setting this to non-zero value keep your SSH sessions alive by forcing a keepalive from the application itself.
Setting this to non-zero value keep your SSH sessions alive by forcing a keepalive from the application itself.