#include "myhead.h"
int sock_fd = -1;
void* fun_send(void* arg)
{
struct ip_mreq zb=*(struct ip_mreq*)arg;
struct sockaddr_in zubo;
zubo.sin_family = AF_INET;
zubo.sin_port = htons(10086);//发送目标
zubo.sin_addr.s_addr = inet_addr("224.10.10.10");
socklen_t zubo_len = sizeof(zubo);
char *buf = malloc(1024);
while (1)
{
memset(buf, 0, 1024);
fgets(buf, 1024, stdin);
sendto(sock_fd, buf, strlen(buf), 0, (struct sockaddr*)&zubo, zubo_len) ;
if(strcmp(buf,"exit\n")==0)
{
struct sockaddr_in local,opposite,broadst;
local.sin_family = AF_INET;
local.sin_port = htons(10086);
local.sin_addr.s_addr = INADDR_ANY;
socklen_t broadst_len=sizeof(broadst);
memset(buf,0,1024);
snprintf(buf,1024,"不知名网友离开了组播...");
sendto(sock_fd,buf,100,0,(struct sockaddr*)&broadst,broadst_len);
//退出组播
setsockopt(sock_fd,IPPROTO_IP,IP_DROP_MEMBERSHIP,&zubo,zubo_len);
break;
}
}
free(buf);
}
int main(int argc, char* argv[])
{
//创建套接字
sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (sock_fd == -1)
{
perror("socket failed");
return -1;
}
//.加入组播组
struct ip_mreq zubo;
zubo.imr_multiaddr.s_addr = inet_addr("224.10.10.10");//224.0.0.1-------239.255.255.255
zubo.imr_interface.s_addr = INADDR_ANY;
socklen_t zubo_len=sizeof(zubo);
//绑定地址
struct sockaddr_in local,opposite,broadst;
local.sin_family = AF_INET;
local.sin_port = htons(10086);
local.sin_addr.s_addr = INADDR_ANY;
socklen_t local_len=sizeof(local);
socklen_t opposite_len =sizeof(opposite);
socklen_t broadst_len=sizeof(broadst);
bind(sock_fd, (struct sockaddr *)&local, local_len);
//加入组播时自动发送一条广播消息
//先开启广播功能
int bt=1;
socklen_t len =sizeof(bt);
setsockopt(sock_fd,SOL_SOCKET,SO_BROADCAST,&bt,len);
//发送消息
char*buf=malloc(100);
memset(buf,0,100);
snprintf(buf,100,"不知名网友加入了组播...");
sendto(sock_fd,buf,100,0,(struct sockaddr*)&broadst,broadst_len);
//创建线程
pthread_t tid;
int pn=pthread_create(&tid, NULL, fun_send, (void*)&zubo) ;
if(pn!=0)
{
perror("创建线程失败");
}
char *recv_buf = malloc(1024);
while (1)
{
memset(recv_buf, 0, 1024);
recvfrom(sock_fd, recv_buf, 1024, 0, (struct sockaddr *)&opposite, &opposite_len);
}
printf("from %s:%d: %s\n", inet_ntoa(opposite.sin_addr), ntohs(opposite.sin_port), recv_buf);
}
08-22
45
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-20
1576
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)