Ubuntu组播 在真机上没有问题,但是放到虚拟机里面,使用桥接方式,就接收不到组播包了,需要手动添加组播路由: sudo add -net 239.255.255.0 netmask 255.255.255.0 dev eth0 相应代码: #include <stdio.h> #include <unistd.h> #include <string.h> #include <arpa/inet.h> #include <net/if.h> #define BUFSIZ 1024 #define PORT 37020 #define GROUP "239.255.255.250" int main(int argc, char *argv[]) { struct sockaddr_in localaddr, from; int confd; ssize_t len, addr_len; char buf[BUFSIZ]; struct ip_mreqn group; /*组播结构体*/ confd = socket(AF_INET, SOCK_DGRAM, 0); bzero(&localaddr, sizeof(localaddr)); /* 初始化*/ localaddr.sin_family = AF_INET; inet_pton(AF_INET, "0.0.0.0" , &localaddr.sin_addr.s_addr); localaddr.sin_port = htons(PORT); bind(confd, (struct sockaddr *)&localaddr, sizeof(localaddr)); inet_pton(AF_INET, GROUP, &group.imr_multiaddr); /* 设置组播组地址*/ inet_pton(AF_INET, "0.0.0.0", &group.imr_address); /*使用本地任意IP添加到组播组*/ group.imr_ifindex = if_nametoindex("eth0"); /* 设置网卡名 编号 ip ad */ setsockopt(confd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &group, sizeof(group));/* 将client加入组播组*/ while (1) { len = recvfrom(confd, buf, sizeof(buf), 0, (struct sockaddr *)&from, &addr_len); write(STDOUT_FILENO, buf, len); sprintf(buf, "good to see you."); len = sendto(confd, buf, strlen(buf), 0, (struct sockaddr *)&from, sizeof(from)); } close(confd); return 0; } (责任编辑:IT) |