networking · advanced · ~15 min

TCP echo client (localhost)

`socket`/`connect`/`read`/`write` against a local peer.

Challenge

Implement int tcp_echo(const char *host, int port, const char *msg, char *out, size_t out_sz) that:

  1. opens a TCP socket to host:port,
  2. writes msg followed by \n,
  3. reads up to out_sz - 1 bytes into out and NUL-terminates,
  4. closes the socket and returns 0 on success.

The grader runs a tiny echo server on 127.0.0.1:<random port> — your client only talks to loopback. Do not connect anywhere else.

Starter code

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

int tcp_echo(const char *host, int port, const char *msg, char *out, size_t out_sz) {
    /* TODO */
    return -1;
}

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