networking · intermediate · ~15 min
Defensive choice of TCP keep-alive interval.
You're building a service that maintains long-lived TCP connections through NATs. Given the expected NAT timeout (in seconds), pick the keep-alive interval that keeps the connection alive without hammering the network.
Implement int suggest_keepalive_interval(int nat_timeout_s) returning the
interval in seconds. The rule:
nat_timeout_s <= 60, return 30 (refresh every 30s on aggressive NATs).nat_timeout_s <= 600, return nat_timeout_s / 2.Special cases: if nat_timeout_s <= 0, return -1 (invalid input).
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.
NAT timeout in seconds.
Interval in seconds (or -1).
Pure arithmetic; no syscalls.
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.