networking · advanced · ~15 min
Non-blocking connect with a wall-clock deadline.
Implement int connect_timeout(const char *host, int port, int ms) that opens a TCP socket to host:port and returns:
ms milliseconds.Use a non-blocking socket and select()/poll() on its writability, or setsockopt(SO_RCVTIMEO/SO_SNDTIMEO). Test against a closed port for the timeout case.
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/select.h>
int connect_timeout(const char *host, int port, int ms) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.