#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
int sock_fd = -1;
void * mem_recv(void *arg)
{
char * argv = (char *)arg;
struct sockaddr_in membership;
membership.sin_family = AF_INET;
membership.sin_port = htons(atoi(argv));
membership.sin_addr.s_addr = inet_addr("225.10.10.10");
socklen_t membership_len = sizeof(membership);
bind(sock_fd,(struct sockaddr *)&membership,membership_len);
char buf[100];
while(1)
{
bzero(buf,100);
fgets(buf,100,stdin);
sendto(sock_fd,buf,100,0,(struct sockaddr *)&membership,membership_len);
}
}
int main(int argc, const char *argv[])
{
//创建套接字
sock_fd = socket(AF_INET,SOCK_DGRAM,0);
if(sock_fd<0)
{
perror("creat socket failed");
return -1;
}
//加入组播
struct ip_mreq membership;
membership.imr_multiaddr.s_addr = inet_addr("225.10.10.10");
membership.imr_interface.s_addr = INADDR_ANY;
socklen_t membership_len = sizeof(membership);
if(setsockopt(sock_fd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&membership,membership_len)<0)
{
perror("creat membership failed");
return -1;
}
//线程(向组播发消息)
pthread_t tid;
pthread_create(&tid,NULL,mem_recv,(void *)&argv[1]);
//给本机地址赋值
struct sockaddr_in local,cilent;
local.sin_family = AF_INET;
local.sin_port = htons(atoi(argv[1]));
local.sin_addr.s_addr = INADDR_ANY;
socklen_t local_len = sizeof(local);
//绑定本地地址到套接字
if(bind(sock_fd,(struct sockaddr *)&local,local_len)<0)
{
if(errno != 98)
{
perror("bind failed");
return -1;
}
}
//接受组播的消息
socklen_t cilent_len =sizeof(cilent);
char buf[100];
while(1)
{
bzero(buf,100);
recvfrom(sock_fd,buf,100,0,(struct sockaddr *)&cilent,&cilent_len);
printf("[%s:%d]%s\n",inet_ntoa(cilent.sin_addr),ntohs(cilent.sin_port),buf);
if(strcmp(buf,"bye\n") == 0)
{
printf("[%s:%d]已退出\n",inet_ntoa(cilent.sin_addr),ntohs(cilent.sin_port));
break;
}
}
return 0;
}
组播互相通信2024-8-21
最新推荐文章于 2024-08-22 23:45:07 发布