在执行过程中,组播的接收程序不能再绑定组播地址,而是0.
实例:
接收端:组播接收端
#include
#include
#include
#include
#include
#include
#include
#include
#define N 64
int main(int argc,char *argv[])
{
int fd;
struct sockaddr_in recad,peerad;
char buf[N]={};
int len;
len=sizeof(peerad);
memset(&recad,0,sizeof(recad));
memset(&peerad,0,sizeof(peerad));
recad.sin_family=PF_INET;
recad.sin_port=htons(atoi(argv[2]));
recad.sin_addr.s_addr=inet_addr(argv[1]);
if((fd=socket(PF_INET,SOCK_DGRAM,0))<0)
{
perror("socket");
exit(-1);
}
if((bind(fd,(struct sockaddr*)&recad,sizeof(recad)))<0)
{
printf("bind");
exit(-1);
}
struct ip_mreq mreq;
memset(&mreq,0,sizeof(mreq));
mreq.imr_multiaddr.s_addr=inet_addr("224.10.10.1");
mreq.imr_interface.s_addr=htons(INADDR_ANY);
if(setsockopt(fd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(mreq))<0)
{
perror("setsockopt");
exit(-1);
}
while(1)
{
memset(buf,0,N);
recvfrom(fd,buf,N,0,(struct sockaddr*)&peerad,&len);
printf("[%s %d] %s\n",inet_ntoa(peerad.sin_addr),ntohs(peerad.sin_port),buf);
}
}
#include
#include
#include
#include
#include
#include
#include
#include
#define N 64
int main(int argc,char *argv[])
{
int fd;
struct sockaddr_in broad;
char buf[N]={"hello everyone!"};
int val=1;
int len;
len=sizeof(val);
memset(&broad,0,sizeof(broad));
broad.sin_family=PF_INET;
broad.sin_port=htons(atoi(argv[2]));
broad.sin_addr.s_addr=inet_addr(argv[1]);
if((fd=socket(PF_INET,SOCK_DGRAM,0))<0)
{
perror("socket");
exit(-1);
}
if(setsockopt(fd,SOL_SOCKET,SO_BROADCAST,&val,len)<0)
{
printf("getsockopt");
exit(-1);
}
while(1)
{
sendto(fd,buf,N,0,(struct sockaddr*)&broad,sizeof(broad));
sleep(1);
}
}
./send 192.168.1.255 8888
接收端:编译:gcc -o recever recever.c
./recever 0 8888
接收端执行时ip一定为0,这样,虽然他是一个组播接收程序,但是还可以接收广播。