networking · intermediate · ~15 min
Defensive choice of TCP keep-alive interval.
A long-lived TCP connection through a NAT gets silently dropped once the NAT's idle timer expires, so a service sends periodic keep-alives. Given the NAT's idle timeout, pick a keep-alive interval that refreshes the mapping in time without flooding the network. This is pure arithmetic — no sockets.
Implement int suggest_keepalive_interval(int nat_timeout_s) that returns the keep-alive interval in seconds, using these rules:
nat_timeout_s <= 60 -> return 30 (aggressive NAT: refresh every 30s).nat_timeout_s <= 600 -> return nat_timeout_s / 2.300 (cap at 5 minutes to save bandwidth).nat_timeout_s <= 0 -> return -1 (invalid input).One int nat_timeout_s — the NAT's idle timeout in seconds.
Returns the suggested interval in seconds, or -1 for invalid (non-positive) input.
suggest_keepalive_interval(60) -> 30
suggest_keepalive_interval(120) -> 60
suggest_keepalive_interval(1800) -> 300
suggest_keepalive_interval(0) -> -1
-1.<=).A long-lived connection without keep-alive will be silently dropped by NAT boxes after a few minutes. Picking the interval is the defensive-server skill nobody teaches.
One integer: the NAT idle timeout in seconds.
The suggested keep-alive interval in seconds, or -1 for non-positive input.
Pure arithmetic; no syscalls. Boundaries 60 and 600 are inclusive.
int suggest_keepalive_interval(int nat_timeout_s) { /* TODO */ (void)nat_timeout_s; return 0; }
Returning the NAT timeout itself — too late by then.
0 or negative input; exactly 60 (boundary); exactly 600 (boundary).
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.