#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
int sock_fd = -1;
struct sockaddr_in broadcast;
char quti = 1;
socklen_t broadcast_len = sizeof(broadcast);
void *sendin(void*agv)
{
struct sockaddr_in opposite = *(struct sockaddr_in*)agv;
socklen_t opposite_len = sizeof(opposite);
//定义缓冲区
char *buf = malloc(100);
while(1)
{
memset(buf,0,100);
recvfrom(sock_fd,buf,100,0,(struct sockaddr*)&opposite,&opposite_len);
printf("from zhubo:%s",buf);
}
pthread_exit((void *)&quti);
}
int main(int argc, const char *argv[])
{
/*判断用户输入合法性
if(argc != 3)
{
printf("请输入一个参数");
return -1;
}*/
//创建套接字
sock_fd = socket(PF_INET,SOCK_DGRAM,0);
if(sock_fd ==-1)
{
perror("creat sock_fd failed:");
return -1;
}
//创建组播结构体
struct ip_mreq zhubo;
//对结构体的成员变量赋值
zhubo.imr_multiaddr.s_addr = inet_addr("225.24.24.24");
zhubo.imr_interface.s_addr = INADDR_ANY;
socklen_t zhubo_len = sizeof(zhubo);
//设置套接字属性
setsockopt(sock_fd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&zhubo,zhubo_len);
//创建本机结构体
struct sockaddr_in local,opposite;
local.sin_family = PF_INET;
local.sin_port = htons(8888);
local.sin_addr.s_addr = htonl(INADDR_ANY);
opposite.sin_family = PF_INET;
opposite.sin_port = htons(8888);
opposite.sin_addr.s_addr =inet_addr("225.24.24.24");
//广播地址结构体
broadcast.sin_family = PF_INET;
broadcast.sin_port = htons(8888);
broadcast.sin_addr.s_addr = inet_addr("192.168.124.255");
socklen_t opposite_len = sizeof(opposite);
socklen_t local_len = sizeof(local);
//绑定函数
bind(sock_fd,(struct sockaddr *)&local,local_len);
//发送一条广播消息
int st = 1;
socklen_t st_len = sizeof(st);
setsockopt(sock_fd,SOL_SOCKET,SO_BROADCAST,&st,st_len);
//定义缓冲区
char *buf = malloc(100);
memset(buf,0,100);
snprintf(buf,100,"本大爷加入组播,速来接驾!!\n");
sendto(sock_fd,buf,100,0,(struct sockaddr *)&broadcast,broadcast_len);
//创建线程
pthread_t tid;
pthread_create(&tid,NULL,sendin,(void*)&opposite);
while(1)
{
memset(buf,0,100);
fgets(buf,100,stdin);
sendto(sock_fd,buf,100,0,(struct sockaddr *)&opposite,opposite_len);
//退出组播
if(strcmp(buf,"bye\n") == 0)
{
//广播消息
memset(buf,0,100);
snprintf(buf,100,"此处不留爷,自有留爷处!!\n");
sendto(sock_fd,buf,100,0,(struct sockaddr *)&broadcast,broadcast_len);
setsockopt(sock_fd,IPPROTO_IP,IP_DROP_MEMBERSHIP,&zhubo,zhubo_len);
break;
}
}
pthread_join(tid,(void *)&quti);
return 0;
}