networking · advanced · ~15 min
Connectionless sockets, `sendto`/`recvfrom`.
Send one UDP datagram to a loopback echo and read the single datagram that comes back.
Implement int udp_roundtrip(const char *host, int port, const char *msg, char *out, size_t out_sz) that sends one UDP datagram containing msg to host:port, waits for one reply datagram, and copies it (NUL-terminated) into out. No main — the grader calls it.
host: an IPv4 address string (always "127.0.0.1" here).port: the UDP port of the echo server.msg: the datagram payload to send.out / out_sz: a writable buffer and its size.Returns 0 on success, -1 on error. After the call out holds the reply bytes, NUL-terminated.
udp_roundtrip("127.0.0.1", port, "dgram", buf, n)
-> returns 0; buf starts with "dgram"
-1.SOCK_DGRAM socket with sendto/recvfrom (no connect needed). Talk only to loopback. Close the socket before returning.host (IPv4 string), port, payload msg, and a writable buffer out of out_sz bytes.
0 on success, -1 on error; out holds the reply datagram, NUL-terminated.
Use SOCK_DGRAM with sendto/recvfrom; loopback only; close the socket before returning.
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stddef.h>
int udp_roundtrip(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.