close(sockfd);
组播(代码)
一、发送端
#include
#include
#include
#include
#include
#include
#include
#include
#include
// ./send 224.0.0.1 8888
int main(int argc, const char *argv[])
{
int ret;
int sockfd;
char packet[1024];
struct sockaddr_in muti_addr;
if (argc < 3){
fprintf(stderr, "Usage: %s \n", argv[0]);
exit(EXIT_FAILURE);
}
// 1. 创建报文套接字
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (-1 == sockfd){
perror("Fail to socket.");
exit(EXIT_FAILURE);
}
// 2. 通过多播地址发送数据包到指定端口
bzero(&muti_addr, sizeof(muti_addr));
muti_addr.sin_family = AF_INET;
muti_addr.sin_port = htons(atoi(argv[2]));
muti_addr.sin_addr.s_addr = inet_addr(argv[1]);
while (1){
putchar('\n');
putchar('>');
fgets(packet, sizeof(packet), stdin);
packet[strlen(packet) - 1] = '\0';
ret = sendto(sockfd, packet, strlen(packet), 0, (struct sockaddr *)&muti_addr, sizeof(muti_addr));
if (-1 == ret){
perror("Fail to sendto.");
break;
}
if (strcmp(packet, "quit") == 0){
break;
}
}
// 3. 关闭套接字
close(sockfd);
return 0;
}
#include
#include
#include
#include
#include
#include
#include
#include
#include
// ./recv 192.168.2.255 8888
int main(int argc, const char *argv[])
{
int ret;
int sockfd;
char packet[1024];
struct sockaddr_in addr;
struct ip_mreq mreq;
struct sockaddr_in peer_addr;
socklen_t addrlen = sizeof(peer_addr);
if (argc < 3){
fprintf(stderr, "Usage: %s \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;
}