networking · advanced · ~15 min
`bind`/`listen`/`accept`; the lifecycle of a listening socket.
Write a minimal TCP server that accepts a single client, echoes its bytes back, and shuts down.
Implement int single_echo_server(int port) that:
127.0.0.1:port,0.No main — the grader calls it.
One int argument port: the loopback port to bind and listen on.
Returns 0 on success, -1 on error. The single connected client receives back the bytes it sent.
single_echo_server(port) while a client sends "ping-pong"
-> returns 0; client reads back "ping-pong"
-1.INADDR_LOOPBACK (local only). Set SO_REUSEADDR. Accept one client, then close the client and listening sockets.One int argument port: the loopback port to bind and listen on.
0 on success, -1 on error; the one client gets its bytes echoed back.
Bind to INADDR_LOOPBACK with SO_REUSEADDR; accept exactly one client; close everything.
#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.