Skip to content

Instantly share code, notes, and snippets.

@MihaelBercic
Last active April 11, 2024 16:57
Show Gist options
  • Save MihaelBercic/557a0386b45e5e912ff493725dfff1f2 to your computer and use it in GitHub Desktop.
Save MihaelBercic/557a0386b45e5e912ff493725dfff1f2 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define MAX_LEN 1024 // Maximum message length
int main() {
int sockfd;
struct sockaddr_in addr;
struct ip_mreq mreq;
char buffer[MAX_LEN + 1];
int bytes_received;
// Create a UDP socket
if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&addr, 0, sizeof(addr));
// Fill in the address structure
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on any interface
addr.sin_port = htons(12345); // Choose any port number you like
// Bind the socket to the address
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// Specify the multicast group to join
mreq.imr_multiaddr.s_addr = inet_addr("224.0.0.251"); // Multicast group address
mreq.imr_interface.s_addr = htonl(INADDR_ANY); // Listen on any interface
// Join the multicast group
if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mreq, sizeof(mreq)) < 0) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
// Receive multicast messages
while (1) {
bytes_received = recvfrom(sockfd, buffer, MAX_LEN, 0, NULL, NULL);
if (bytes_received < 0) {
perror("recvfrom failed");
exit(EXIT_FAILURE);
}
buffer[bytes_received] = '\0'; // Null-terminate the received data
printf("Received message: %s\n", buffer);
}
// Close the socket
close(sockfd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment