Networking in C · advanced · ~10 min

Socket timeouts

Cap blocking operations with a deadline.

Lesson

By default read/recv on a blocking socket can wait forever. Three ways to bound it:

  1. setsockopt(SO_RCVTIMEO) for read timeout (also SO_SNDTIMEO).
  2. Make the socket non-blocking and use select/poll with a timeout.
  3. Schedule a SIGALRM with alarm(seconds) (older, less flexible).

Code examples

struct timeval tv = { .tv_sec = 5, .tv_usec = 0 };
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);