networking · advanced · ~15 min

One-shot TCP server

`bind`/`listen`/`accept`; the lifecycle of a listening socket.

Challenge

Write a minimal TCP server that accepts a single client, echoes its bytes back, and shuts down.

Task

Implement int single_echo_server(int port) that:

  1. binds to 127.0.0.1:port,
  2. listens with backlog 1,
  3. accepts exactly one client,
  4. reads up to 256 bytes and writes them back to that client,
  5. closes everything and returns 0.

No main — the grader calls it.

Input

One int argument port: the loopback port to bind and listen on.

Output

Returns 0 on success, -1 on error. The single connected client receives back the bytes it sent.

Example

single_echo_server(port) while a client sends "ping-pong"
  ->   returns 0; client reads back "ping-pong"

Edge cases

  • Any socket/bind/listen/accept failure returns -1.

Rules

  • Bind to INADDR_LOOPBACK (local only). Set SO_REUSEADDR. Accept one client, then close the client and listening sockets.

Input format

One int argument port: the loopback port to bind and listen on.

Output format

0 on success, -1 on error; the one client gets its bytes echoed back.

Constraints

Bind to INADDR_LOOPBACK with SO_REUSEADDR; accept exactly one client; close everything.

Starter code

#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

int single_echo_server(int port) {
    /* TODO */
    return -1;
}

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