Just one server to listen multicast port, and then transfer it to the same port, then all hosts on network can get the multicast message. Because the client just can send the message to host not to network, so need the server transfer it.
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define IPNAME "239.255.255.250"
#define PORT 1900
int cmpIp(char* clientip);
int main(int argc, char ** argv)
{
int fd_listen;
struct sockaddr_in serverAddr;
struct sockaddr_in client;
char buffer[2048*2] = {0};
int data_len, salen;
salen = sizeof(serverAddr);
/* server address */
bzero(&serverAddr, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
fd_listen = socket(PF_INET, SOCK_DGRAM, 0);
if (fd_listen < 0)
{
perror("socket error");
exit(1);
}
/*reuse the socket*/
int opt = SO_REUSEADDR;
setsockopt(fd_listen, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if (bind(fd_listen, (struct sockaddr *)&serverAddr, salen) < 0)
{
perror("bind error: ");
exit(1);
}
/*join a multycast group*/
struct ip_mreq mreq;
serverAddr.sin_addr.s_addr = inet_addr(IPNAME);
memcpy (&mreq.imr_multiaddr, &(serverAddr.sin_addr),sizeof(struct in_addr));
setsockopt(fd_listen, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(struct ip_mreq));
while (1)
{
memset(buffer,0,sizeof(buffer));
data_len = recvfrom (fd_listen, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, &salen);
if (data_len <= 0)
{
perror("socket closed by remote client");
close(fd_listen);
exit(0);
}
buffer[data_len] = 0;
//printf("client ip is %s\n", (char*)inet_ntoa(client.sin_addr));
/*to judge if the client is server itself*/
if (cmpIp((char*)inet_ntoa(client.sin_addr)) < 0)
{
memset(&client, 0, sizeof(client));
continue;
}
//printf("recv msg lenth=%d, content is : %s\n",data_len, buffer);
//printf("resend the msg\n");
if (sendto(fd_listen, (char *)buffer, data_len, 0, (struct sockaddr *)&serverAddr, salen) <=0 )
{
perror("cann't send to remote server");
close(fd_listen);
exit(0);
}
}
return 0;
}
int cmpIp(char* clientip)
{
char hostname[200],**pptr;
char ipaddr[50];
struct utsname utname;
struct hostent *hptr;
uname(&utname);
strcpy(hostname,utname.nodename);
if ((hptr = gethostbyname(hostname)) == NULL)
{
exit(-1);
}
pptr = hptr->h_addr_list;
while(*pptr != NULL) {
inet_ntop(AF_INET,*pptr,ipaddr,30);
if(strcmp( ipaddr, clientip) == 0)
return -1;
pptr++;
}
return 0;
}
阅读(1616) | 评论(0) | 转发(0) |