networking · beginner · ~12 min · safe pentest lab
Bind a TCP socket to loopback, set SO_REUSEADDR, and put it in listen mode.
A listening TCP server must issue its setup calls in a specific order. Given the sequence of calls as opcodes (1=socket, 2=setsockopt, 3=bind, 4=listen), decide whether it is a valid server setup:
int valid_listen_setup(const int *steps, int n);
Return 1 iff: exactly one socket first, then zero or more setsockopt, then exactly one bind, then exactly one listen, and nothing after the listen.
One helper, used by every TCP server you'll ever write. Master the four-call prologue once and you stop fumbling it.
steps is an array of n opcodes (1–4).
1 if the sequence is a valid server setup, else 0.
socket must come first and listen last; bind exactly once before listen; setsockopt (e.g. SO_REUSEADDR) is optional and only before bind.
#include <stddef.h>
/* Steps are opcodes: 1=socket 2=setsockopt 3=bind 4=listen. Return 1 iff the
sequence is a valid server setup: exactly one socket first, then zero or more
setsockopt, then exactly one bind, then exactly one listen, and nothing after. */
int valid_listen_setup(const int *steps, int n){ (void)steps;(void)n; 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.