1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
void DLL_EXPORT sendMulticast(unsigned char *send_str, int send_len, int type, int port, char *group)
{
int sock; /* socket descriptor */
struct sockaddr_in mc_addr; /* socket address structure */
struct sockaddr_in mc_addr2; /* socket bind structure */
char *mc_addr_str; /* multicast IP address */
unsigned short mc_port; /* multicast port */
unsigned char mc_ttl=1; /* time to live (hop count) */
mc_addr_str = group; /* arg 1: multicast IP address */
mc_port = port; /* arg 2: multicast port number */
/* create a socket for sending to the multicast address */
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
/* set the TTL (time to live/hop count) for the send */
setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, (char*) &mc_ttl, sizeof(mc_ttl));
int flag_on = 1; /* socket option flag */
/* Make the socket reusable,
any other socket must be set with this option if they use the same port */
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&flag_on, sizeof(flag_on));
/* construct a multicast address structure */
memset(&mc_addr, 0, sizeof(mc_addr));
mc_addr.sin_family = AF_INET;
mc_addr.sin_addr.s_addr = inet_addr(mc_addr_str);
mc_addr.sin_port = htons(mc_port);
/* construct socket bind structure*/
memset(&mc_addr2, 0, sizeof(mc_addr));
mc_addr2.sin_family = AF_INET;
mc_addr2.sin_addr.s_addr = htons(INADDR_ANY);
mc_addr2.sin_port = htons(mc_port);
/* bind the port in order to set the source port */
bind(sock, (SOCKADDR*) &mc_addr2, sizeof(mc_addr2));
/* send to the multicast group "group" on the port "port" from the port "port" */
sendto(sock, (char *)send_str, send_len, 0, (struct sockaddr *) &mc_addr, sizeof(mc_addr));
/* close the socket */
closesocket(sock);
} |
Partager