组播在内核里面对应的一个重要的结构体是ip_mreq,如下:
struct ip_mreq { struct in_addr imr_multiaddr; /* IP multicast address of group */ struct in_addr imr_interface; /* local IP address of interface */ };
而一台服务器上可能有多个网卡,系统要允许用户使用其中的某个网卡加入某一个主机组,imr_interface参数就是指定一个特定的设备接口,
告诉协议栈只想在这个设备所在的子网中加入某个组播组。有了这两个参数,协议栈就能知道:在哪个网络设备接口上加入哪个组播组。
下面是一个组播的例子:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <arpa/inet.h> #include <linux/if.h> #include <linux/route.h> #include <netinet/ether.h> #include <netpacket/packet.h> #include "server.h" bool mySystem(const char *command) { int status; status = system(command); if (-1 == status) { printf("mySystem: system error!"); return false; } else { if (WIFEXITED(status)) { if (0 == WEXITSTATUS(status)) { return true; } printf("mySystem: run shell script fail, script exit code: %d ", WEXITSTATUS(status)); return false; } printf("mySystem: exit status = [%d] ", WEXITSTATUS(status)); return false; } } void fillRspHead(char *buff, char type) { if (type == 'g') { memcpy(buff, "getmac|", 7); } else if (type == 's') { memcpy(buff, "setip|", 6); } else { printf("fillRspHead: invalid command type! "); return; } } void fillSN(char *buff) { FILE *fp; int bufflen = strlen(buff); if((fp=fopen(SN_FILE, "r")) == NULL) { strcat(buff, "|"); perror("getSN: fopen"); return; } fgets(buff + bufflen, NETLEN, fp); while(buff[strlen(buff) - 1] == ' ' || buff[strlen(buff) - 1] == ' ') { buff[strlen(buff) - 1] = '