linux网络编程组播,linux网络编程(组播)

\n", argv[0]);

exit(EXIT_FAILURE);

}

// 1. 创建报文套接字

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

if (-1 == sockfd){

perror("Fail to socket.");

exit(EXIT_FAILURE);

}

//加入组

mreq.imr_multiaddr.s_addr = inet_addr(argv[1]);

mreq.imr_interface.s_addr = INADDR_ANY;

ret = setsockopt(sockfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(mreq));

if(-1 == ret){

perror("fail to setsockopt");

exit(EXIT_FAILURE);

}

// 2. 绑定广播地址和端口

bzero(&addr, sizeof(addr));

addr.sin_family = AF_INET;

addr.sin_port = htons(atoi(argv[2]));

// broad_addr.sin_addr.s_addr = inet_addr(argv[1]);

addr.sin_addr.s_addr = INADDR_ANY;

ret = bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));

if (-1 == ret){

perror("Fail to bind.");

exit(EXIT_FAILURE);

}

while (1){

// 3. 接收

ret = recvfrom(sockfd, packet, sizeof(packet), 0, (struct sockaddr *)&peer_addr, &addrlen);

if (-1 == ret){

perror("Fail to recvfrom.");

break;

}

packet[ret] = '\0';

printf("---------------------------------------\n");

printf("ip : %s\n", inet_ntoa(peer_addr.sin_addr));

printf("port : %d\n", ntohs(peer_addr.sin_port));

printf("recv(%d) : %s\n", ret, packet);

printf("---------------------------------------\n");

if (strcmp(packet, "quit") == 0){

break;

}

}

// 4. 关闭套接字

close(sockfd);

return 0;

}

你可能感兴趣的:(linux网络编程组播)