Broadcast & Multicast Socket Programming
Idea in plain words
Unicast transmits packets to a single destination host; Broadcast transmits to all hosts on a local subnet; Multicast transmits to an interested group.
Explanation
Broadcast sends datagrams to every host on a subnet, forcing non-interested hosts to process interrupts and examine packets up to the transport layer before discarding them. Multicasting remedies this by assigning a Class D multicast IP mapped to Ethernet multicast MAC addresses (01:00:5e:xx:xx
). Network interface cards (NICs) filter out irrelevant multicast packets in hardware. Applications join a multicast group by passing struct ip_mreq to setsockopt(), allowing routers and local switches to prune transmission trees.Key points
- Broadcast addresses: Limited broadcast (255.255.255.255) and subnet-directed broadcast (e.g., 192.168.1.255).
- SO_BROADCAST socket option must be explicitly enabled using setsockopt() to permit broadcast transmission.
- IPv4 Multicast uses Class D addresses (224.0.0.0 to 239.255.255.255); managed dynamically by IGMP (Internet Group Management Protocol).
- Joining a multicast group uses setsockopt() with IP_ADD_MEMBERSHIP and struct ip_mreq.
Example
Example
NTP (Network Time Protocol) and service discovery protocols (SSDP/mDNS) use multicasting to advertise server presence without flooding the entire subnet.
Code examples
// Enable Broadcasting
int on = 1;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on));
// Join Multicast Group
struct ip_mreq mreq;
inet_pton(AF_INET, "239.255.0.1", &mreq.imr_multiaddr.s_addr);
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
Exam questions
- [8 Marks] Compare Unicast, Broadcast, and Multicast communication. Explain how a process joins a multicast group in C.
- [5 Marks] Why is the SO_BROADCAST socket option required? What are the security and bandwidth implications of broadcast storms?