networking · advanced · ~15 min

TCP connect with timeout

Non-blocking connect with a wall-clock deadline.

Challenge

Implement int connect_timeout(const char *host, int port, int ms) that opens a TCP socket to host:port and returns:

  • 0 on successful connect,
  • -1 on error,
  • -2 if the connect does not complete within 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.

Starter code

#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.