搞一个组播聊天室,组播地址自己指定,
任何人都可以加入组播,有成员加入的时候,
广播发一条消息,加上自己的IP和端口。组播收发消息
退出的组播地址的时候,广播发一条消息,加上自己的IP和端口。
#include "/home/ubuntu/myhead.h"
void *to_multi(void *arg);
/*
struct ip_mreq
{
struct in_addr imr_multiaddr; //组播地址
struct in_addr imr_interface; //本机地址
}
struct in_addr imr_multiaddr
{
s_addr;//组播地址
}
struct in_addr imr_interface
{
s_addr;//本机地址
}
*/
/*
1.搞一个组播聊天室,组播地址自己指定,
任何人都可以加入组播,有成员加入的时候,
广播发一条消息,加上自己的IP和端口。组播收发消息
退出的组播地址的时候,广播发一条消息,加上自己的IP和端口。
*/
int sock_fd = -1;
int main(int argc,char **argv)
{
//1.创建套接字
sock_fd = socket(AF_INET,SOCK_DGRAM,0);
//2.加入组播组
struct ip_mreq m;
//组播地址范围:
//224.0.0.1~224.255.255.255
m.imr_multiaddr.s_addr = inet_addr("224.10.10.20");
//本机地址
m.imr_interface.s_addr = INADDR_ANY;
socklen_t m_len = sizeof(m);
setsockopt(sock_fd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&m,m_len);
//3.绑定IP
//opposite---对端,local----本机
struct sockaddr_in local,opposite;
local.sin_family = AF_INET;
local.sin_port = htons(9999);
local.sin_addr.s_addr = INADDR_ANY;
socklen_t local_len = sizeof(local);
socklen_t opposite_len = sizeof(opposite);
//绑定本机
bind(sock_fd,(struct sockaddr *)&local,local_len);
//发送一条广播消息
int bt = 1;
socklen_t len = sizeof(bt);
//套接字开启广播功能
int ret = setsockopt(sock_fd,SOL_SOCKET,SO_BROADCAST,&bt,len);
if(-1 == ret)
{
perror("open broadcast failed!");
return -1;
}
char *buf = malloc(100);
memset(buf,0,100);
//广播地址结构体
struct sockaddr_in broadcast;
broadcast.sin_family = AF_INET;
broadcast.sin_port = htons(9999);
broadcast.sin_addr.s_addr = inet_addr("192.168.124.255");
socklen_t broadcast_len = sizeof(broadcast);
snprintf(buf,100,"来自IP:%s 端口号:%d已加入 数据为:%s",inet_ntoa(broadcast.sin_addr),ntohs(broadcast.sin_port),buf);
//创建线程
pthread_t tid;
pthread_create(&tid,NULL,to_multi,(void*)&m);
while(1)
{
//主线程接收消息
memset(buf,0,100);
recvfrom(sock_fd,buf,100,0,(struct sockaddr *)&opposite,&opposite_len);
printf("接收到的消息%s\n",buf);
//pthread_join();//会阻塞等待
}
}
void *to_multi(void *arg)
{
//子线程发消息
//往组播地址发消息
char *buf = malloc(100);
struct sockaddr_in multi;
multi.sin_family = AF_INET;
multi.sin_port = htons(9999);
multi.sin_addr.s_addr = inet_addr("224.10.10.20");
socklen_t multi_len = sizeof(multi);
//发送消息不需要绑定,直接发送
while(1)
{//结构体传参
struct ip_mreq m = *(struct ip_mreq*)arg;
socklen_t m_len = sizeof(m);
memset(buf,0,100);
fgets(buf,100,stdin);
sendto(sock_fd,buf,100,0,(struct sockaddr*)&multi,multi_len);
//退出组播
if(strcmp(buf,"byebye\n") == 0)
{
//退出组播组
//发送广播一条消息
struct sockaddr_in broadcast;
snprintf(buf,100,"来自IP:%s 端口号:%d已退出 数据为:%s",inet_ntoa(broadcast.sin_addr),ntohs(broadcast.sin_port),buf);
setsockopt(sock_fd,IPPROTO_IP,IP_DROP_MEMBERSHIP,&m,m_len);
break;
}
}
}