#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MULTICAST_ADDR "239.0.0.1"
#define PORT 8888
#define BUFSIZE 1024
int main(int argc, char** argv) {
int sock;
struct sockaddr_in addr;
char buf[BUFSIZE];
int recv_len;
struct ip_mreq mreq;
int enable = 1;
// 멀티캐스트 소켓 생성
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
perror("Failed to create socket");
exit(EXIT_FAILURE);
}
// 멀티캐스트 TTL 설정
setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &enable, sizeof(enable));
// 멀티캐스트 그룹에 참여
mreq.imr_multiaddr.s_addr = inet_addr(MULTICAST_ADDR);
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
// 소켓 주소 설정
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(PORT);
// 소켓 바인드
if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
perror("Failed to bind socket");
exit(EXIT_FAILURE);
}
// 데이터 수신 및 출력
while (1) {
memset(buf, 0, BUFSIZE);
recv_len = recv(sock, buf, BUFSIZE, 0);
if (recv_len < 0) {
perror("Failed to receive data");
exit(EXIT_FAILURE);
}
printf("Received data: %s\n", buf);
}
// 소켓 닫기
close(sock);
return 0;
}