networking · advanced · ~15 min
Non-blocking connect with a wall-clock deadline.
Attempt a TCP connect but give up after a deadline, so a dead peer cannot block you forever.
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.
host: an IPv4 address string (loopback in tests).port: the TCP port to connect to.ms: the connect timeout in milliseconds.0, -1, or -2 as defined above.
connect_timeout("127.0.0.1", closed_port, 300) -> -1 or -2
-1 (refused) or -2 (timed out) quickly.select/poll on writability (or SO_RCVTIMEO/SO_SNDTIMEO). Check SO_ERROR to confirm success after the socket becomes writable.host (IPv4 string), port, and a timeout ms in milliseconds.
0 on connect, -1 on error, -2 on timeout.
Non-blocking connect with select/poll on writability; never block past ms.
#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.