IPv4 UDP Broadcast

Whilst doing some networking code recently, I came by something I didn’t know about, UDP Broadcasting.

With TCP, both clients have knowledge of each other once a connection is formed. Because of this, you cannot just send a message to anyone listening, there has to be someone there.

With UDP, the host can transmit packets whether or not clients are connected and listening or not, and it will only know if they are there if it is listening and they are transmitting. But the client has to know about the host to begin listening.

Just like there is 127.0.0.1 (known as the loopback address) to send packets back to itself, 255.255.255.255 (known as the broadcast address) will allow packets to be sent to all addresses listening to a port.

Here is some basic code for sending and receive a broadcast.

//
const in_port_t broadcastPort = 12345;
 
//
void broadcast_send()
{
	// ooo datagrams
	int sockfd = socket(PF_INET, SOCK_DGRAM, 0);
 
	//
	struct sockaddr_in broadcastAddress;
	memset(&broadcastAddress, 0, sizeof(broadcastAddress));
	{
		broadcastAddress.sin_family = AF_INET;
		broadcastAddress.sin_addr.s_addr = htonl(INADDR_BROADCAST);
		broadcastAddress.sin_port = htons(broadcastPort);
	}
 
	// allow broadcasts
	const int enableBroadcast = 1;
	setsockopt(sockfd, SOL_SOCKET,SO_BROADCAST, &enableBroadcast, sizeof(enableBroadcast));
 
	// send to broadcast address
	const char message[] = "Test";
	sendto(sockfd, message, sizeof(message), 0, (struct sockaddr *)&broadcastAddress, sizeof(broadcastAddress));
}
 
//
void broadcast_receive()
{
	const size_t kMaxMessageLength = 200;
	char message[kMaxMessageLength];
 
	// ooo datagrams
	int sockfd = socket(PF_INET, SOCK_DGRAM, 0);
 
	//
	struct sockaddr_in recv_addr;
	memset(&recv_addr, 0, sizeof(recv_addr));
	{
		recv_addr.sin_family      = AF_INET;
		recv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
		recv_addr.sin_port        = htons(broadcastPort);
	}
 
	//
	bind(sockfd, (struct sockaddr *)&recv_addr, sizeof(recv_addr));
 
	// allow broadcasts
	const int enableBroadcast = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &enableBroadcast, sizeof(enableBroadcast));
 
	// receive
	struct sockaddr_in senderAddress;
	socklen_t senderLength = sizeof(senderAddress);
 
	ssize_t length = recvfrom(sockfd,
				  message, kMaxMessageLength,
				  0,
				  (struct sockaddr *)&senderAddress, &senderLength);
 
	if(length >= 0)
	{
		printf("Message received: %s\n", message);
	}
}

When a packet is sent using the broadcast address, all attached network hosts that are listening on the port will receive the packet.

This can be used for LAN multiplayer, as a way of advertising a game being available to join, or to seek games that are looking for players.