局域网小组群播
头文件/宏定义
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <time.h>
#include <pthread.h>
#define MULTICAST_GROUP "223.255.255.555"
#define PORT 8888
函数1
/********************************************************************
*
* name : receive_thread
* function :
* argument :
* @n :arg
*
* retval : none
* author : 17647576169@163.com
* date : 2024年6月4日
* note :
*
* *****************************************************************/
void *receive_thread(void *arg)
{
int sockfd = *(int *)arg;
char buffer[1024];
struct sockaddr_in source_addr;
socklen_t addr_len = sizeof(source_addr);
while (1)
{
ssize_t len = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&source_addr, &addr_len);
if (len < 0)
{
perror("接收数据失败");
continue;
}
buffer[len] = '\0';
char *source_ip = inet_ntoa(source_addr.sin_addr);
time_t current_time;
struct tm *time_info;
char formatted_time[20];
time(¤t_time);
time_info = localtime(¤t_time);
strftime(formatted_time, sizeof(formatted_time), "%Y-%m-%d %H:%M:%S", time_info);
printf("来自 %s 的消息,时间:%s,内容:%s\n", source_ip, formatted_time, buffer);
}
return NULL;
}
函数1
/********************************************************************
*
* name : send_thread
* function :
* argument :
* @n :arg
*
* retval : none
* author : 17647576169@163.com
* date : 2024年6月4日
* note :
*
* *****************************************************************/
void *send_thread(void *arg)
{
int sockfd = *(int *)arg;
char message[1024];
struct sockaddr_in dest_addr;
socklen_t addr_len = sizeof(dest_addr);
memset(&dest_addr, 0, sizeof(dest_addr));
dest_addr.sin_family = AF_INET;
dest_addr.sin_addr.s_addr = inet_addr(MULTICAST_GROUP);
dest_addr.sin_port = htons(PORT);
while (1)
{
printf("请输入要发送的消息:");
fgets(message, sizeof(message), stdin);
sendto(sockfd, message, strlen(message), 0, (struct sockaddr *)&dest_addr, addr_len);
}
return NULL;
}
主函数
int main(int argc, char const *argv[])
{
int sockfd;
struct sockaddr_in addr;
struct ip_mreq mreq;
// 创建套接字
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
perror("创建套接字失败");
exit(EXIT_FAILURE);
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(PORT);
// 绑定套接字
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("绑定套接字失败");
close(sockfd);
exit(EXIT_FAILURE);
}
mreq.imr_multiaddr.s_addr = inet_addr(MULTICAST_GROUP);
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
// 加入多播组
if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
{
perror("加入多播组失败");
close(sockfd);
exit(EXIT_FAILURE);
}
printf("等待数据...\n");
pthread_t receive_tid, send_tid;
pthread_create(&receive_tid, NULL, receive_thread, &sockfd);
pthread_create(&send_tid, NULL, send_thread, &sockfd);
// 等待线程结束
pthread_join(receive_tid, NULL);
pthread_join(send_tid, NULL);
close(sockfd);
return 0;
}