networking · advanced · ~15 min

UDP send and receive

Connectionless sockets, `sendto`/`recvfrom`.

Challenge

Send one UDP datagram to a loopback echo and read the single datagram that comes back.

Task

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.

Input

  • 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.

Output

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

Example

udp_roundtrip("127.0.0.1", port, "dgram", buf, n)
  ->   returns 0; buf starts with "dgram"

Edge cases

  • Any socket/sendto/recvfrom failure returns -1.

Rules

  • Use a SOCK_DGRAM socket with sendto/recvfrom (no connect needed). Talk only to loopback. Close the socket before returning.

Input format

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

Output format

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

Constraints

Use SOCK_DGRAM with sendto/recvfrom; loopback only; 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 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.