networking · intermediate · ~15 min · safe pentest lab

One-shot echo server

Accept → recv → send → close, all on the same per-client fd.

Challenge

Write the classic first server: accept one client, read what they send, send it straight back, hang up.

Task

Implement int echo_once(int listening_fd) that handles exactly one connection:

  1. Accept one connection on listening_fd.
  2. Read up to 256 bytes from the client.
  3. Send those bytes back unchanged.
  4. Close the per-client fd.

Input

  • listening_fd: an already-bound, already-listening TCP socket (the grader opens it on 127.0.0.1).

Output

Return the number of bytes echoed back to the client, or -1 on any failure (failed accept, recv error, or send error).

Example

client connects and sends "ping" (4 bytes)
  -> echo_once returns 4, and the client reads back "ping"

Edge cases

  • A client that sends 0 bytes: nothing to echo, return 0.
  • Always close the per-client fd, even on the success path.

Why this matters

The traditional first server. Accept one client, read whatever they send, write it back, close.

Input format

listening_fd: a bound, listening TCP socket on 127.0.0.1.

Output format

The number of bytes echoed back, or -1 on any failure.

Constraints

Read at most 256 bytes; send them back unchanged; close the client fd before returning.

Starter code

#include <sys/socket.h>
#include <unistd.h>
int echo_once(int listening_fd) {
    /* TODO */
    return -1;
}

Background lessons

Up next

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