networking · advanced · ~15 min

TCP connect with timeout

Non-blocking connect with a wall-clock deadline.

Challenge

Attempt a TCP connect but give up after a deadline, so a dead peer cannot block you forever.

Task

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

  • 0 on a successful connect,
  • -1 on error,
  • -2 if the connect does not complete within ms milliseconds.

No main — the grader calls it.

Input

  • host: an IPv4 address string (loopback in tests).
  • port: the TCP port to connect to.
  • ms: the connect timeout in milliseconds.

Output

0, -1, or -2 as defined above.

Example

connect_timeout("127.0.0.1", closed_port, 300)   ->   -1 or -2

Edge cases

  • Connecting to a closed local port must NOT block forever: it returns -1 (refused) or -2 (timed out) quickly.

Rules

  • Use a non-blocking socket with select/poll on writability (or SO_RCVTIMEO/SO_SNDTIMEO). Check SO_ERROR to confirm success after the socket becomes writable.

Input format

host (IPv4 string), port, and a timeout ms in milliseconds.

Output format

0 on connect, -1 on error, -2 on timeout.

Constraints

Non-blocking connect with select/poll on writability; never block past ms.

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.