Created
May 12, 2014 07:27
-
-
Save zhanghongquan/ffa9a1a1e7ca6875d36f to your computer and use it in GitHub Desktop.
multicast on all network interface (only linux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/types.h> | |
#include <ifaddrs.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <arpa/inet.h> | |
#include <netinet/in.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <string.h> | |
#include <stdio.h> | |
bool multicast( const char* ip, unsigned short port, const char* data, size_t size, int ttl, bool loopback ) { | |
struct sockaddr_in groupaddr; | |
struct in_addr localinterface; | |
memset(&groupaddr, 0 , sizeof(groupaddr) ); | |
groupaddr.sin_family = AF_INET; | |
groupaddr.sin_addr.s_addr = inet_addr(ip); | |
groupaddr.sin_port = htons(port); | |
struct ifaddrs *addrs = 0; | |
if( getifaddrs( &addrs ) ) { | |
return false; | |
} | |
if ( !addrs ) | |
return false; | |
struct ifaddrs* temp = addrs;//for freeifaddrs | |
unsigned long loaddr = inet_addr("127.0.0.1"); | |
bool bOK = false; | |
while( addrs != 0 ) { | |
struct sockaddr* soaddr = addrs->ifa_addr; | |
const char* ifname = addrs->ifa_name; | |
addrs = addrs->ifa_next; | |
if(!soaddr || soaddr->sa_family != AF_INET ) | |
continue; | |
if( ((struct sockaddr_in*)soaddr)->sin_addr.s_addr == loaddr ) | |
continue; | |
//printf("broadcast on %s\n", ifname); | |
int sock = socket( AF_INET, SOCK_DGRAM, 0 ); | |
if( !sock ) | |
return false; | |
localinterface.s_addr = ((struct sockaddr_in*)soaddr)->sin_addr.s_addr; | |
if(setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, (char *)&localinterface, sizeof(localinterface)) < 0) { | |
close(sock); | |
continue; | |
} | |
char loop = loopback ? 1 : 0; | |
if( setsockopt( sock, IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&loop, sizeof(loop)) < 0 ) { | |
close(sock); | |
continue; | |
} | |
if( sendto( sock, data, size, 0 , (struct sockaddr*)&groupaddr, sizeof(groupaddr) ) == size ) { | |
bOK = true; | |
} | |
close(sock); | |
}; | |
freeifaddrs(temp); | |
return bOK; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment