#include
#include
#include
#include
#include
#include
#include
struct in_addr localInterface;
struct sockaddr_in groupSock;
int sd;
int main (int argc, char **argv)
{
char databuf[1024] = "1111111111111111111111111111";
int datalen = strlen(databuf);
if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("Opening datagram socket error");
exit(1);
}
/* Initialize the group sockaddr structure with a */
/* group address of 226.1.1.1 and port 4321. */
memset((char *) &groupSock, 0, sizeof(groupSock));
groupSock.sin_family = AF_INET;
groupSock.sin_addr.s_addr = inet_addr("226.1.1.1");
groupSock.sin_port = htons(4321);
/* Send a message to the multicast group specified by the*/
/* groupSock sockaddr structure. */
if(sendto(sd, databuf, datalen, 0, (struct sockaddr*)&groupSock, sizeof(groupSock)) < 0)
{
perror("Sending datagram message error");
}
else
printf("Sending datagram message...OK\n");
return 0;
}
================================================================
#include
#include
#include
#include
#include
#include
#include
struct sockaddr_in localSock;
struct ip_mreq group;
int sd;
int datalen;
char databuf[1024];
int main(int argc, char *argv[])
{
/* Create a datagram socket on which to receive. */
if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("Opening datagram socket error");
exit(1);
}
/* Bind to the proper port number with the IP address */
/* specified as INADDR_ANY. */
memset((char *)&localSock, '\0', sizeof(localSock));
localSock.sin_family = AF_INET;
localSock.sin_port = htons(4321);
localSock.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sd, (struct sockaddr*)&localSock, sizeof(localSock)))
{
perror("Binding datagram socket error");
close(sd);
exit(1);
}
/* Join the multicast group 226.1.1.1 on the local 203.106.93.94 */
/* interface. Note that this IP_ADD_MEMBERSHIP option must be */
/* called for each local interface over which the multicast */
/* datagrams are to be received. */
group.imr_multiaddr.s_addr = inet_addr("226.1.1.1");
group.imr_interface.s_addr = htonl(INADDR_ANY);
if(setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&group, sizeof(group)) < 0)
{
perror("Adding multicast group error");
close(sd);
exit(1);
}
/* Read from the socket. */
datalen = sizeof(databuf);
if(read(sd, databuf, datalen) < 0)
{
perror("Reading datagram message error");
close(sd);
exit(1);
}
else
printf("The message from multicast client is: %s\n", databuf);
return 0;
}
阅读(1052) | 评论(0) | 转发(0) |