networking · beginner · ~12 min · safe pentest lab
Bind a TCP socket to loopback, set SO_REUSEADDR, and put it in listen mode.
Every TCP server begins with the same four-call sequence: socket → setsockopt → bind → listen. Wrap that sequence into one helper that returns a ready-to-accept listening socket on loopback.
Implement int open_listener(int port) that creates a TCP socket, binds it to 127.0.0.1:port, and puts it in listen mode.
The function must:
AF_INET, SOCK_STREAM).SO_REUSEADDR (before bind) so a quick restart does not fail with EADDRINUSE.127.0.0.1:port.listen(fd, 16).-1 on any failure.One int port. Pass port = 0 to let the kernel pick a free ephemeral port (the harness does this to avoid collisions).
Returns a non-negative listening file descriptor on success, or -1 if any step fails.
open_listener(0) -> fd >= 0, bound to 127.0.0.1 on a kernel-chosen port
port = 0: the kernel assigns a free port (check it with getsockname).-1.INADDR_LOOPBACK (127.0.0.1), never INADDR_ANY — traffic must never leave the machine.SO_REUSEADDR before bind.One helper, used by every TCP server you'll ever write. Master the four-call prologue once and you stop fumbling it.
One integer port. 0 means 'let the kernel pick a free port'.
A non-negative listening fd on success, -1 on any failure.
Bind to INADDR_LOOPBACK only (never INADDR_ANY). Set SO_REUSEADDR before bind. Close the fd on every error path.
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
int open_listener(int port) {
/* TODO */
return -1;
}
Forgetting SO_REUSEADDR. Using INADDR_ANY (breaks the loopback-only rule). Missing htons/htonl.
port=0 (kernel picks). port<1024 without root (EACCES). port already taken (EADDRINUSE).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.