networking · advanced · ~15 min
`socket`/`connect`/`read`/`write` against a local peer.
Write a minimal TCP client that connects to a loopback echo server, sends a message, and reads the reply.
Implement int tcp_echo(const char *host, int port, const char *msg, char *out, size_t out_sz) that:
host:port,msg followed by \n,out_sz - 1 bytes into out and NUL-terminates it,0 on success.No main — the grader calls it.
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.Returns 0 on success, -1 on error. After the call out holds the echoed bytes, NUL-terminated.
tcp_echo("127.0.0.1", port, "hello", buf, n)
-> returns 0; buf starts with "hello"
-1.127.0.0.1:<random port>. Connect only to loopback — do not connect anywhere else. Close the socket before returning.host (IPv4 string), port, message msg, and a writable buffer out of out_sz bytes.
0 on success, -1 on error; out holds the echoed reply, NUL-terminated.
Connect only to loopback; send msg plus a newline; close the socket before returning.
#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.