代码如下:
#include "fun_interface.h"
#include <unistd.h>
#include <string>
struct in_addr localInterface;
struct sockaddr_in groupSock;
int sd;
char databuf[1024] = "Multicast test message lol!";
int datalen = sizeof(databuf);
typedef struct {
std::string dip;
int sock;
struct sockaddr_in gsock;
} test_item_t;
test_item_t sock_items[] = {
{
.dip = "225.0.0.128"
},
{
.dip = "225.0.0.120"
},
{
.dip = "225.0.0.111"
},
{
.dip = "225.0.0.110"
},
{
.dip = "239.202.0.11"
},
{
.dip = "239.202.255.251"
}
};
int init_sock()
{
int sd;
int items_size = sizeof(sock_items)/sizeof(test_item_t);
printf("== size:%d\n",items_size);
for(int i = 0;i < items_size;i ++) {
sd = socket(AF_INET, SOCK_DGRAM, 0);
if(sd < 0) {
perror("Opening datagram socket error");
return -1;
} else {
printf("open socket ....ok\n");
sock_items[i].sock = sd;
}
memset((char *) &sock_items[i].gsock, 0, sizeof(sock_items[i].gsock));
sock_items[i].gsock.sin_family = AF_INET;
//groupSock.sin_addr.s_addr = inet_addr("226.1.1.1");
sock_items[i].gsock.sin_addr.s_addr = inet_addr(sock_items[i].dip.c_str());
sock_items[i].gsock.sin_port = htons(4321);
localInterface.s_addr = inet_addr("192.168.1.12");
//localInterface.s_addr = inet_addr("172.16.16.90");
if(setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF, (char *)&localInterface, sizeof(localInterface)) < 0){
perror("Setting local interface error");
return -1;
}else
printf("Setting the local interface...OK\n");
}
return 0;
}
int main()
{
int items_size = sizeof(sock_items)/sizeof(test_item_t);
if(init_sock() != 0) {
exit(1);
}
/* Send a message to the multicast group specified by the*/
/* groupSock sockaddr structure. */
/*int datalen = 1024;*/
for(int i = 0;i < 100;i ++) {
for(int j = 0;j < items_size;j ++ ) {
if(sendto(sock_items[j].sock, databuf, datalen, 0, (struct sockaddr*)&sock_items[j].gsock, sizeof(sock_items[j].gsock)) < 0) {
perror("Sending datagram message error");
} else
printf("Sending datagram message...OK\n");
}
sleep(3);
}
return 0;
}
|