SoFunction
Updated on 2025-04-14

Detailed explanation of C++ implementation of broadcast communication

Everyone knows the concept very clearly and will not elaborate on it.

Broadcasting must use UDP.

The setsockopt() function and its application in broadcast:

In C++ network programming, the setsockopt() function is used to set socket options that control the various behaviors of sockets. For broadcast communications, we are particularly concerned with the SO_BROADCAST option, which allows sockets to send broadcast messages.

setsockopt() function prototype

int setsockopt(int sockfd, int level, int option_name, const void *option_value, socklen_t option_len);

sockfd: The socket descriptor to set the options.

level: Specify the protocol layer where the option is located. For most socket options, this layer is SOL_SOCKET, indicating that the options are related to the socket layer itself.

option_name: The name of the option to be set. For broadcast options, this is SO_BROADCAST.

option_value: Pointer to a variable containing the value of the option to be set. For SO_BROADCAST, this value is usually an integer, non-zero means broadcasting is enabled and zero means disable (although disabling broadcasting is not usually required, as it may be disabled by default unless specifically enabled).

option_len: option_value The length of the variable pointed to in bytes. For SO_BROADCAST, this is usually sizeof(int).

SO_BROADCAST option

Function: Allows sockets to send broadcast messages. A broadcast message is a message sent to all hosts on the network that listen for specific broadcast addresses and ports.

Default: On most systems, sockets do not allow broadcast messages by default and must be enabled explicitly.

Usage scenario: Broadcasting is useful when you want to send the same information to multiple hosts on the network. For example, when looking for a service or device in a LAN.

Framework sample code

Here is a sample code for how to enable the SO_BROADCAST option using setsockopt() in C++:

#include <sys/>
#include <sys/>
#include <netinet/>
#include <>
#include <>
 
int main() {
    int sockfd;
    int broadcastEnable = 1; // Enable broadcast 
    // Create UDP socket    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        perror("socket creation failed");
        return 1;
    }
 
    // Enable broadcast options    if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable)) < 0) {
        perror("setsockopt(SO_BROADCAST) failed");
        close(sockfd);
        return 1;
    }
 
    // ... Send a broadcast message here ... 
    // Close the socket    close(sockfd);
    return 0;
}

In this example, we first create a UDP socket and then enable the SO_BROADCAST option using the setsockopt() function. After that, we can use the sendto() function to send broadcast messages. Finally, we closed the socket.

The complete broadcast process:

Using sockets for broadcast communication in C++ usually involves the following steps:

  • Create socket: Use the socket() function to create a UDP socket because UDP supports broadcasting.
  • Set broadcast options: Use the setsockopt() function to enable broadcast options.
  • Bind socket (optional): If you want to bind to a specific port and/or IP address, you can use the bind() function.
  • Send broadcast messages: Use the sendto() function to send the message to the broadcast address (usually 255.255.255.255).

Here is a simple example code showing how to use sockets for broadcast communication in C++:

#include <iostream>
#include <cstring>
#include <arpa/>
#include <>
#include <sys/>
#include <sys/>
#include <netinet/>
 
#define PORT 8080
#define BROADCAST_IP "255.255.255.255"
#define BUFFER_SIZE 1024
 
int main() {
    int sockfd;
    struct sockaddr_in broadcastAddr;
    const char *message = "Hello, this is a broadcast message!";
    char buffer[BUFFER_SIZE];
 
    // Create UDP socket    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }
 
    int broadcastEnable = 1;
    // Enable broadcast options    if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable)) < 0) {
        perror("setsockopt(SO_BROADCAST) failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }
 
    // Set the broadcast address and port    memset(&broadcastAddr, 0, sizeof(broadcastAddr));
    broadcastAddr.sin_family = AF_INET;
    broadcastAddr.sin_addr.s_addr = inet_addr(BROADCAST_IP);
    broadcastAddr.sin_port = htons(PORT);
 
    // Send broadcast messages    if (sendto(sockfd, message, strlen(message), MSG_CONFIRM, (const struct sockaddr*)&broadcastAddr, sizeof(broadcastAddr)) < 0) {
        perror("sendto failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }
 
    std::cout << "Broadcast message sent: " << message << std::endl;
 
    // Close the socket    close(sockfd);
 
    return 0;
}

Things to note

  • Permissions: On some operating systems (such as Linux), sending broadcast messages may require administrator permissions. If you encounter permission issues, you can try running the program as root, or use the sudo command.
  • Firewall: Ensure that the firewall settings allow the sending and receiving of broadcast messages.
  • Network configuration: Ensure that the network configuration allows broadcast communication.

Receive broadcast messages

To receive broadcast messages, you need to create a socket that listens for a specific port and address (usually INADDR_ANY) and then wait for data to be received. Here is a simple example of receiving broadcast messages:

#include <iostream>
#include <cstring>
#include <arpa/>
#include <>
#include <sys/>
#include <sys/>
#include <netinet/>
 
#define PORT 8080
#define BUFFER_SIZE 1024
 
int main() {
    int sockfd;
    struct sockaddr_in serverAddr, clientAddr;
    socklen_t addrLen = sizeof(clientAddr);
    char buffer[BUFFER_SIZE];
 
    // Create UDP socket    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }
 
    // Bind the socket to the specified port    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(PORT);
 
    if (bind(sockfd, (const struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
        perror("bind failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }
 
    // Receive broadcast messages    ssize_t numBytes = recvfrom(sockfd, buffer, BUFFER_SIZE - 1, MSG_WAITALL, (struct sockaddr*)&clientAddr, &addrLen);
    if (numBytes < 0) {
        perror("recvfrom failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }
 
    buffer[numBytes] = '\0';
    std::cout << "Received broadcast message: " << buffer << std::endl;
 
    // Close the socket    close(sockfd);
 
    return 0;
}

This receiver will listen for the specified port and print the received broadcast message. Make sure that the receiver and sending programs run in the same network environment and that the port numbers match.

Here the server socket is bound to the specified port (PORT, i.e. 8080), and it is ready to receive datagrams from any IP address (because serverAddr.sin_addr.s_addr is set to INADDR_ANY). Since the socket is of UDP type and no specific broadcast reception option is set (in fact, receiving broadcast messages is enabled by default for UDP sockets), the socket is able to receive any UDP datagrams sent to the port, including broadcast messages.

However, the code itself does not specifically specify that it only receives messages from a particular broadcast address. When the recvfrom() function is called, it blocks (unless the socket is set to non-blocking mode) until a datagram reaches the bound port. Once the datagram arrives, recvfrom() will populate the clientAddr structure to reflect the sender's IP address and port number.

To know the broadcast address of the actual source of the broadcast message, you can check the clientAddr.sin_addr field. This field contains the sender's IP address. If this is a broadcast message, it should be the broadcast address on your network (such as 255.255.255.255 for local broadcasts, or a subnet specific broadcast address, such as 192.168.1.255 for subnet 192.168.1.0/24). However, note that if the sender is not in the same subnet and is a broadcast message sent through the router (this is usually not allowed because broadcast messages are not usually routed across subnets), then clientAddr may display the sender's actual IP address, not the broadcast address.

In practical applications, if you want to receive messages on a specific broadcast address, you usually need to have a known broadcast address on the network, and your application needs to know this address. However, due to the local nature of UDP broadcasting, your application can usually only receive broadcast messages from within the same subnet unless there is a special routing configuration that allows broadcast across subnets.

In addition, it is worth noting that in modern network environments, many networks are configured to not allow or limit the propagation of broadcast messages due to security and maintenance reasons. Therefore, you may want to consider these factors when actually deploying an application based on UDP broadcast.

This is the end of this article about the detailed explanation of C++ broadcast communication. For more related C++ broadcast communication content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!