写一下linux c语言组播收发代码
时间: 2024-12-22 17:22:08 浏览: 6
在Linux环境下编写C语言程序来处理组播通信涉及到使用socket API和IP multicast功能。以下是一个简单的示例,展示了如何创建套接字、加入组播组并发送接收数据:
```c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define GROUP_IP "192.168.1.1" // 组播地址
#define PORT 5000
#define GROUP_PORT PORT
void join_group(int sock) {
struct ip_mreq imreq;
imreq.imr_multiaddr.s_addr = inet_addr(GROUP_IP);
imreq.imr_interface.s_addr = htonl(INADDR_ANY); // 使用环回接口
setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imreq, sizeof(imreq));
}
int main() {
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // 创建UDP套接字
if (sock < 0) {
perror("Failed to create socket");
return 1;
}
char message[] = "Hello, Group!";
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(GROUP_PORT);
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
bind(sock, (struct sockaddr *)&server_address, sizeof(server_address));
printf("Joining group %s on port %d\n", GROUP_IP, GROUP_PORT);
join_group(sock);
sendto(sock, message, strlen(message), 0, (struct sockaddr *)&server_address, sizeof(server_address)); // 发送消息
while (true) { // 接收数据
char buffer[1024];
ssize_t bytes_received = recvfrom(sock, buffer, sizeof(buffer), 0, NULL, NULL);
if (bytes_received > 0) {
printf("Received data: %.*s\n", (int)bytes_received, buffer);
} else {
perror("Error receiving data");
break;
}
}
close(sock);
return 0;
}
```
这个示例假设你已经在本地网络上有一个运行着监听该组播端口的应用正在发送数据。请注意,实际应用中可能需要添加错误检查和更多的细节。
阅读全文