UDP and peer discovery
chatterd learns to find peers it was never told about: UDP multicast beacons on 239.23.7.1, the IP_ADD_MEMBERSHIP / IP_MULTICAST_TTL setsockopt dance, a small gossip protocol deduped by name, and the bridge from a discovered datagram to the canonical chatterd TCP chat frame; proven across two libvirt guests with tcpdump, ss -uap, and both transcripts.
Learning objectives
By the end of this chapter you can:
- Open and configure a UDP multicast socket with
IP_ADD_MEMBERSHIP,IP_MULTICAST_IF,IP_MULTICAST_TTL, andIP_MULTICAST_LOOPto join and send to an administratively-scoped group. - Explain why connectionless, message-oriented, best-effort UDP suits discovery while TCP suits the conversation that follows, and why a beacon must stay inside one unfragmented MTU.
- Dedupe repeated beacons by peer name and bridge a first-seen discovery into a TCP dial carrying the existing canonical chat frame.
- Coordinate shutdown of a blocking UDP receive loop with a socket read
timeout plus a stop signal (
stop_token, cancelledcontext, orAtomicBool, depending on language). - Verify multicast group membership and socket state with
ip maddrandss -uap, and capture beacons on the wire withtcpdump -X. - Run a two-host discovery exchange across a libvirt bridge and explain why a TTL-1 multicast beacon stays link-local without any NAT configuration.
Why this matters
A peer that has to be told every address in advance does not scale past a
demo: real services find each other. UDP multicast gives one sendto a way
to reach every listener in a group without the sender knowing who or how many
they are, and the dedup-then-dial pattern this chapter builds, a
connectionless announcement bridged into a connection-oriented conversation,
is the shape behind most service-discovery protocols you will meet later,
whatever their wire format.
The chapter also draws a hard line worth keeping: discovery tolerates loss and reorder, so it belongs on UDP, while the conversation that follows needs ordering and reliability, so it belongs on TCP. Picking the wrong protocol for either half either drops messages you needed or pays connection overhead you did not.
chatterd already runs on TCP, carrying the canonical chat
frame (magic "CH", version, type, a big-endian length, and a payload)
between two endpoints you already knew, since you typed the peer’s
address on the command line. This chapter removes that assumption. chatterd
discover finds peers it was never told about, and the primitive that makes
that possible is the one TCP cannot offer: UDP multicast, a single
sendto that reaches every listener in a group without the sender knowing
who (or how many) they are. The shape of the chapter is a bridge: a
connectionless UDP beacon announces “I exist, dial me here,” a receiver hears
strangers and dedupes them, and the first time it meets a new name it opens
an ordinary TCP connection and speaks the same canonical chat frame already
introduced: the header never changes; each version only adds message
types. Discovery is UDP; the conversation stays TCP. The star of the
run is real: two libvirt guests, systems-target and systems-peer, each
discovering the other across the virbr0 bridge.
The code is in examples/23-udp-and-peer-discovery/. ./demo.sh there builds
all three implementations; its README.md specifies the CLI, the byte-exact
beacon and frame formats, and the exit codes all three languages share.
Tools used:
ss,tcpdump,ip,strace(host);tcpdump,ss,ip maddr(systems-target / systems-peer VMs, run live in this chapter);tcplife/tcpconnect/offcputimebcc-tools (lab VM, exercised in Part 8). Everything host-side is checked byscripts/check-host.shor ships with Fedora; the VM tools ship in the lab cloud-init.
Why UDP, and why the datagram stays small
TCP gives you a reliable, ordered byte stream over an established
connection; every one of those words is a cost. A connection is state on both
ends and a three-way handshake before the first byte; reliability means
retransmit timers and buffering; ordering means head-of-line blocking. For
discovery you want the opposite of all of it. You do not know who your peers
are, so there is nobody to connect to; you want one announcement to reach
many; and you do not care if a single beacon is lost, because another one
follows in 200 ms. That is UDP: connectionless, message-oriented, best-effort.
sendto hands the kernel one datagram, it goes on the wire as one IP packet
(or a fragmented set), and the receiver’s recv returns it whole or not at
all: message boundaries are preserved, unlike a TCP stream where you must
re-frame yourself. Loss and reorder are possible and, for a beacon, harmless:
a dropped beacon just means “discovered one round later.”
The datagram stays small: chatterd’s beacon is one ASCII line
(CHATTERD1 <name> <tcp-port> <host-ip>), 34 or 35 bytes on the wire in the
run below, far under the ~1472-byte non-fragmenting payload of a 1500-byte
MTU. Keeping a beacon inside one un-fragmented packet is a real discipline:
UDP has no reassembly guarantee beyond IP’s, so a beacon that fragments turns
one lost fragment into a wholly lost beacon. Small, self-describing, and
idempotent is the whole design.
Multicast versus broadcast. Broadcast (255.255.255.255 or a subnet
directed broadcast) reaches every host on the segment whether it cares or
not, and routers rightly drop it. Multicast is opt-in: a datagram addressed
to a group in 239.0.0.0/8 (the administratively-scoped block) is delivered
only to sockets that have joined that group, via IP_ADD_MEMBERSHIP. Three
more socket options shape the send: IP_MULTICAST_IF pins which interface the
beacon leaves by (it matters on a multi-homed host), IP_MULTICAST_TTL = 1
keeps it on the local link so no router forwards it, and IP_MULTICAST_LOOP
controls whether this host’s other sockets also receive it, the switch that
makes the local two-process demo work over loopback and is irrelevant across
two machines, where the packet is on the wire regardless.
How the code works
The multicast socket is the heart of the chapter, and all three languages run
the same four-option dance around it (join the group, pin the outgoing
interface, enable loopback, set TTL 1), differing only in how thick the
library wrapper is. Here it is verbatim from
examples/23-udp-and-peer-discovery/:
std::expected<Fd, std::string> make_multicast_socket(in_addr group, in_addr iface,
std::uint16_t port) {
Fd fd(::socket(AF_INET, SOCK_DGRAM, 0));
if (!fd) return std::unexpected(errno_msg("socket(udp)"));
int one = 1;
if (::setsockopt(fd.get(), SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
return std::unexpected(errno_msg("SO_REUSEADDR"));
sockaddr_in bind_addr{};
bind_addr.sin_family = AF_INET;
bind_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind_addr.sin_port = htons(port);
if (::bind(fd.get(), reinterpret_cast<sockaddr*>(&bind_addr), sizeof(bind_addr)) < 0)
return std::unexpected(errno_msg("bind(udp)"));
ip_mreq mreq{};
mreq.imr_multiaddr = group;
mreq.imr_interface = iface;
if (::setsockopt(fd.get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
return std::unexpected(errno_msg("IP_ADD_MEMBERSHIP"));
if (::setsockopt(fd.get(), IPPROTO_IP, IP_MULTICAST_IF, &iface, sizeof(iface)) < 0)
return std::unexpected(errno_msg("IP_MULTICAST_IF"));
unsigned char loop = 1;
if (::setsockopt(fd.get(), IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)) < 0)
return std::unexpected(errno_msg("IP_MULTICAST_LOOP"));
unsigned char ttl = 1;
if (::setsockopt(fd.get(), IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) < 0)
return std::unexpected(errno_msg("IP_MULTICAST_TTL"));
set_rcv_timeout(fd.get(), 200);
return fd;
}
func makeSender(ip4 [4]byte) (int, error) {
fd, err := unix.Socket(unix.AF_INET, unix.SOCK_DGRAM, 0)
if err != nil {
return -1, fmt.Errorf("socket: %w", err)
}
if err := unix.SetsockoptInet4Addr(fd, unix.IPPROTO_IP, unix.IP_MULTICAST_IF, ip4); err != nil {
unix.Close(fd)
return -1, fmt.Errorf("IP_MULTICAST_IF: %w", err)
}
if err := unix.SetsockoptByte(fd, unix.IPPROTO_IP, unix.IP_MULTICAST_LOOP, 1); err != nil {
unix.Close(fd)
return -1, fmt.Errorf("IP_MULTICAST_LOOP: %w", err)
}
if err := unix.SetsockoptByte(fd, unix.IPPROTO_IP, unix.IP_MULTICAST_TTL, 1); err != nil {
unix.Close(fd)
return -1, fmt.Errorf("IP_MULTICAST_TTL: %w", err)
}
return fd, nil
}
fn make_multicast(cfg: &Config) -> Fallible<UdpSocket> {
let sock = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
sock.set_reuse_address(true)?;
let bind = SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, cfg.port);
sock.bind(&SockAddr::from(bind))?;
sock.join_multicast_v4(&cfg.group, &cfg.iface)?;
sock.set_multicast_if_v4(&cfg.iface)?;
sock.set_multicast_loop_v4(true)?;
sock.set_multicast_ttl_v4(1)?;
sock.set_read_timeout(Some(Duration::from_millis(200)))?;
Ok(sock.into())
}
Three spellings, one syscall sequence. The C++ version is the raw form and
shows every step: bind to INADDR_ANY on the group port (you bind the
port, not the group address, so every group joined on that port arrives),
then the four setsockopt calls. SO_REUSEADDR matters because two
chatterd processes on one host must both bind the same UDP port; without it
the second bind fails EADDRINUSE. The ip_mreq carries two addresses:
imr_multiaddr is the group to join, imr_interface is the local interface
address to join it on: get that wrong on a multi-homed box and the kernel
drops group traffic before your socket ever sees it. Rust’s socket2 collapses
the same calls into named methods (join_multicast_v4, set_multicast_ttl_v4)
and then into()s the socket to a plain std::net::UdpSocket, an OwnedFd
it can share across threads. Go splits the roles: the receiver is built by
net.ListenMulticastUDP (which does the join for you), while the beacon
sender is this separate raw unix.Socket with the three send-side options
set explicitly: the standard library has no one-call multicast sender, so it
drops to golang.org/x/sys/unix. Note the SO_RCVTIMEO / set_read_timeout
of 200 ms on every receive socket: it is not about beacons, it is the escape
hatch that lets each blocking recv wake periodically to re-check the stop
flag at shutdown.
The rest is small. The announce loop (in main/discover) formats the
beacon once (CHATTERD1 <name> <tcp-port> <iface>) and sendtos it to the
group --rounds times, --announce-ms apart. The receive loop reads a
datagram, splits on whitespace, requires exactly four fields with tok[0] ==
"CHATTERD1", ignores any beacon whose name equals its own, parses the peer’s
port and IP, and consults a dedup set so a peer is announced once no matter
how many of its beacons arrive. On first sight it prints `discovered peer
verified: evidence produced
this session on the Fedora 44 reference host (kernel 7.1) and the
two lab guests systems-target (192.168.124.7) /
systems-peer (192.168.124.95): the runner printed
23-udp-and-peer-discovery PASS PASS PASS
(3 passed, 0 failed, 0 skipped) under --mode vm; the host
loopback run produced the exact alice/bob
discovered peer and peer … says: lines, with
ss -uap showing the UNCONN 0.0.0.0:51833 fd-4 socket
and ip maddr show lo the joined group. On the two guests,
tcpdump -X on systems-peer captured both beacons to
239.23.7.1.51824 (34 B CHATTERD1 peer 9241
192.168.124.95 and 35 B CHATTERD1 target 9241 192.168.124.7,
IP-header TTL byte 01); ss -uanp showed the joined
chatterd fd-4 UDP socket and ip maddr show enp1s0 the
239.23.7.1 membership; and both guests' stdout printed one
discovered peer and one peer … says: line as quoted.
No special libvirt NAT configuration was required: the guests share one virbr0
L2 segment. The bcc-tools tcpconnect/tcplife/offcputime
callout is unverified as marked and is exercised in Part 8.