Networking in C · advanced · ~10 min
Put a deadline on blocking socket operations so they can't wait forever.
By default, read or recv on a blocking socket (one that pauses your program until data arrives) can wait forever. If the other side never sends anything, your program hangs.
The fix is to set a deadline. There are three common ways to do this.
setsockopt with SO_RCVTIMEO — Sets a read timeout directly on the socket. There is also SO_SNDTIMEO for send timeouts. This is the simplest option.select or poll — Make the socket non-blocking, then wait for it to become ready using select or poll with a timeout. This gives you the most control.SIGALRM with alarm(seconds) — Schedule a signal that interrupts the blocked call after a set number of seconds. This is the older approach and is less flexible.struct timeval tv = { .tv_sec = 5, .tv_usec = 0 };
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);