Lesson 17 of 18 Data on the Wire

UDP Broadcast Packets in C

Send one UDP packet to every host on your LAN: SO_BROADCAST, limited vs subnet-directed broadcast addresses, discovery patterns, and multicast for IPv6.

30-40 min intermediate 0/18 lessons done
Course contents Lesson 17 of 18 · 0 done
On this page (10 sections)
  1. What you will learn
  2. One packet, every host
  3. Which address?
  4. SO_BROADCAST: the safety catch
  5. The broadcaster
  6. Discovery pattern
  7. IPv6 and multicast
  8. Key takeaways
  9. Exercises
  10. Quiz

What you will learn

  • What a broadcast packet is and where it can (and can’t) go.
  • The two broadcast addresses and how to compute your subnet’s.
  • Why sendto() fails with EACCES until you set SO_BROADCAST.
  • How discovery protocols use broadcast, and what IPv6 uses instead.

One packet, every host

Normally a UDP datagram goes to one address (unicast). A broadcast datagram is delivered to every host on the local network segment, and each host that has a socket bound to the destination port receives a copy. DHCP uses this to find a server before a machine even has an address; games and printers use it to find each other on a LAN.

Broadcast is:

  • UDP only. TCP needs exactly one peer.
  • IPv4 only. IPv6 removed broadcast in favour of multicast.
  • Local only. Routers don’t forward broadcasts, so they stay within your subnet.
  • Expensive. Every host on the segment must process the packet, even ones that don’t care. Use it sparingly.

Which address?

AddressNameReaches
255.255.255.255Limited broadcastEvery host on the directly attached network of the sending interface
Network address with all host bits set, e.g. 192.168.1.255 for 192.168.1.0/24Subnet-directed broadcastEvery host on that subnet

To compute the subnet broadcast address, OR the network address with the inverted netmask (from lesson 2): broadcast = (addr & mask) | ~mask. ip addr on Linux shows it as brd.

On machines with several interfaces, the subnet-directed form gives you control over which network the packet goes to.

SO_BROADCAST: the safety catch

To stop a program from flooding the network by accident, the kernel refuses to send to a broadcast address unless the socket has opted in. Without the option, sendto() fails with EACCES (“Permission denied”).

int yes = 1;
setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &yes, sizeof yes);

The broadcaster

/* announce.c - broadcast a UDP "who is out there?" message on the local network.
 * Usage: ./announce 255.255.255.255 6060 "hello lan"   (or a subnet broadcast like 192.168.1.255) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>

int main(int argc, char *argv[])
{
    if (argc != 4) {
        fprintf(stderr, "usage: %s broadcast-address port message\n", argv[0]);
        return 1;
    }

    int fd = socket(AF_INET, SOCK_DGRAM, 0);   /* broadcast is IPv4-only */
    if (fd == -1) {
        perror("socket");
        return 1;
    }

    int yes = 1;                       /* without this, sendto() fails with EACCES */
    if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &yes, sizeof yes) == -1) {
        perror("setsockopt SO_BROADCAST");
        return 1;
    }

    struct sockaddr_in to;
    memset(&to, 0, sizeof to);
    to.sin_family = AF_INET;
    to.sin_port = htons((uint16_t)atoi(argv[2]));
    if (inet_pton(AF_INET, argv[1], &to.sin_addr) != 1) {
        fprintf(stderr, "not an IPv4 address: %s\n", argv[1]);
        return 1;
    }

    ssize_t n = sendto(fd, argv[3], strlen(argv[3]), 0, (struct sockaddr *)&to, sizeof to);
    if (n == -1)
        perror("sendto");
    else
        printf("broadcast %zd bytes to %s:%s\n", n, argv[1], argv[2]);

    close(fd);
    return n == -1;
}

The receiver needs nothing special: any UDP socket bound to the port (with the wildcard address) receives broadcasts. The sensor_listen program from lesson 11 works as-is:

./sensor_listen 6060                         # on one or more machines on the LAN
./announce 255.255.255.255 6060 "hello lan"  # from any machine on the LAN

Run several listeners on different machines and they all print the message. To run more than one listener on the same machine and port, each needs SO_REUSEADDR (or SO_REUSEPORT on some systems) before bind().

Discovery pattern

Broadcast shines for “who’s out there?”:

  1. A client broadcasts DISCOVER myservice to a known port.
  2. Each server that offers the service replies unicast to the sender’s address (from recvfrom()), e.g. HERE myservice 7070.
  3. The client collects replies for a short window (say 500 ms) and lists the servers.

Only the question is broadcast; answers go straight back, which keeps network load low.

IPv6 and multicast

IPv6 has no broadcast. The replacement is multicast: hosts explicitly join a group address (ff02::... on the local link, for example) with setsockopt(IPV6_JOIN_GROUP), and only members receive the traffic. IPv4 has multicast too (224.0.0.0/4, joined with IP_ADD_MEMBERSHIP). mDNS/Bonjour discovery works this way. Multicast is gentler on the network, so prefer it for new designs.

Key takeaways

  • Broadcast sends one UDP datagram to every host on the local IPv4 subnet; routers don’t forward it.
  • Use 255.255.255.255 or the subnet-directed address (addr & mask) | ~mask.
  • Set SO_BROADCAST or sendto() fails with EACCES.
  • Broadcast the question, unicast the answers; use multicast for IPv6 and new protocols.

Exercises

  1. Remove the setsockopt() call from announce.c and confirm the EACCES error.
  2. Use getifaddrs() to list each IPv4 interface with its ifa_broadaddr, and broadcast to each one.
  3. Build the discovery pattern: a find_servers client that broadcasts and prints every unicast reply received within 500 ms, and a responder that answers it.

Quiz

  1. What is the subnet-directed broadcast address of 10.1.4.77/22?
  2. Why does sendto() to 255.255.255.255 fail with “Permission denied” on a fresh socket?
  3. Why don’t broadcast packets reach hosts on the other side of your router?
Show answers
  1. The mask is 255.255.252.0; the network is 10.1.4.0; the broadcast address is 10.1.7.255.
  2. The socket hasn’t set SO_BROADCAST, a deliberate safety catch.
  3. Routers don’t forward broadcasts by design; otherwise one packet could flood every connected network.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).