Cooperative Discovery Using UDP Broadcasts

Multicast tends to be seen as more modern and “better” than broadcast. In IPv6, broadcast doesn’t work at all: you always have to use multicast. Nonetheless, all IPv4 local network discovery protocols end up using UDP broadcast anyhow. The reason: broadcast and multicast end up working much the same, except broadcast is simpler and less risky. Multicast is seen by network admins as kind of dangerous, as it can leak over network segments.

If you’ve never used UDP, you’ll discover it’s quite a nice protocol. In some ways it reminds me of ØMQ, sending whole messages to peers using two different patterns: one-to-one and one-to-many. The main problems with UDP are that (a) the POSIX socket API was designed for universal flexibility, not simplicity, (b) UDP messages are limited for practical purposes to about 512 bytes, and (c) when you start to use UDP for real data you’ll find that a lot of messages get dropped, especially as infrastructure tends to favor TCP over UDP.

Example 8-1 is a minimal ping program that uses UDP instead of ICMP_ECHO.

Example 8-1. UDP discovery, model 1 (udpping1.c)

//
//  UDP ping command
//  Model 1, does UDP work inline
//
#include <czmq.h>
#define PING_PORT_NUMBER 9999
#define PING_MSG_SIZE    1
#define PING_INTERVAL    1000  //  Once per second

static void
derp (char *s)
{
    perror (s);
    exit (1);
}

int main (void)
{
    zctx_t *ctx = zctx_new ();

    //  Create UDP socket
    int fd;
    if ((fd = socket (AF_INET, SOCK_DGRAM

Get ZeroMQ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.