networking · beginner · ~12 min · safe pentest lab

Validate a server setup sequence

Bind a TCP socket to loopback, set SO_REUSEADDR, and put it in listen mode.

Challenge

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.

Why this matters

One helper, used by every TCP server you'll ever write. Master the four-call prologue once and you stop fumbling it.

Input format

steps is an array of n opcodes (1–4).

Output format

1 if the sequence is a valid server setup, else 0.

Constraints

socket must come first and listen last; bind exactly once before listen; setsockopt (e.g. SO_REUSEADDR) is optional and only before bind.

Starter code

#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; }

Common mistakes

Forgetting SO_REUSEADDR. Using INADDR_ANY (breaks the loopback-only rule). Missing htons/htonl.

Edge cases to handle

port=0 (kernel picks). port<1024 without root (EACCES). port already taken (EADDRINUSE).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.