写一个c语言组播收发数据的例子
时间: 2024-12-18 09:32:01 浏览: 17
在C语言中,由于原生标准库并不直接支持组播功能,我们通常需要借助于网络编程库,如socket API或者更高级的libevent、libuv等。下面是一个简单的UDP(User Datagram Protocol)组播收发数据的例子,它使用了socket编程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MAX_PACKET_SIZE 1024
void send_group_message(char *message, char *group_ip, int port) {
struct sockaddr_in server;
socklen_t addrlen = sizeof(server);
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == -1) {
perror("Error creating socket");
exit(1);
}
server.sin_family = AF_INET;
inet_pton(AF_INET, group_ip, &server.sin_addr);
server.sin_port = htons(port);
if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(ttl)) == -1) {
perror("Error setting multicast TTL");
}
if (sendto(sock, message, strlen(message), 0, (struct sockaddr *)&server, addrlen) == -1) {
perror("Error sending data to group");
}
close(sock);
}
void receive_group_message(char *buffer, size_t bufsize, char *group_ip, int port) {
struct sockaddr_in source;
socklen_t len = sizeof(source);
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&reuseaddr, sizeof(reuseaddr));
if (bind(sock, (struct sockaddr *)&source, len) == -1) {
perror("Error binding to receive port");
}
if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *)&mreq, sizeof(mreq)) == -1) {
perror("Error joining multicast group");
}
while (true) {
ssize_t bytes_received = recvfrom(sock, buffer, bufsize, 0, (struct sockaddr *)&source, &len);
if (bytes_received > 0) {
printf("Received message from %s:%d: %s\n", inet_ntoa(source.sin_addr), ntohs(source.sin_port), buffer);
} else {
perror("Error receiving data");
break;
}
}
close(sock);
}
int main() {
char message[] = "Hello, Group!";
char group_ip[] = "224.0.0.1"; // 组播IP地址,如"224.0.0.1"
int port = 5000; // 发送端和接收端相同的端口
int ttl = 1; // 设置TTL(Time To Live),用于限制消息传播范围
bool reuseaddr = 1; // 设置SO_REUSEADDR标志
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr = inet_addr(group_ip);
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
send_group_message(message, group_ip, port);
receive_group_message(buffer, MAX_PACKET_SIZE, group_ip, port);
return 0;
}
```
注意:这个例子假设你已经在系统上配置了组播功能,并且运行程序的主机连接到同一子网内的组播路由器。同时,为了能够成功发送和接收,接收端也需要加入相应的组播组。
阅读全文