networking · advanced · ~15 min

TCP echo client (localhost)

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

Challenge

Write a minimal TCP client that connects to a loopback echo server, sends a message, and reads the reply.

Task

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 it,
  4. closes the socket and returns 0 on success.

No main — the grader calls it.

Input

  • host: an IPv4 address string (always "127.0.0.1" here).
  • port: the TCP port of the echo server.
  • msg: the message to send.
  • out / out_sz: a writable buffer and its size.

Output

Returns 0 on success, -1 on error. After the call out holds the echoed bytes, NUL-terminated.

Example

tcp_echo("127.0.0.1", port, "hello", buf, n)
  ->   returns 0; buf starts with "hello"

Edge cases

  • Any socket/connect/read/write failure returns -1.

Rules

  • The grader runs the echo server on 127.0.0.1:<random port>. Connect only to loopback — do not connect anywhere else. Close the socket before returning.

Input format

host (IPv4 string), port, message msg, and a writable buffer out of out_sz bytes.

Output format

0 on success, -1 on error; out holds the echoed reply, NUL-terminated.

Constraints

Connect only to loopback; send msg plus a newline; close the socket before returning.

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.