![](https://img-blog.csdnimg.cn/direct/abfd790b55fb4b9f921231b717ab74c9.png)
{
int rfd=socket(AF_INET,SOCK_DGRAM,0);
if(rfd==-1)
{
perror("socket");
return -1;
}
struct ip_mreqn imr;
imr.imr_multiaddr.s_addr=inet_addr("224.1.2.3");
imr.imr_address.s_addr=inet_addr("192.168.125.116");
imr.imr_ifindex=0;
if(setsockopt(rfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&imr,sizeof(imr))==-1)
{
perror("setsockopt");
return -1;
}
struct sockaddr_in rin;
rin.sin_family=AF_INET;
rin.sin_addr.s_addr=inet_addr("224.1.2.3");
rin.sin_port=htons(5555);
if(bind(rfd,(struct sockaddr*)&rin,sizeof(rin))==-1)
{
perror("bind");
return -1;
}
char rbuf[128]="";
while(1)
{
bzero(rbuf,sizeof(rbuf));
recv(rfd,rbuf,sizeof(rbuf),0);
printf("收到广播:%s\n",rbuf);
if(strcmp(rbuf,"OVER")==0)
{
break;
}
}
close(rfd);
return 0;
}
{
int sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd==-1)
{
perror("sfd");
return -1;
}
struct sockaddr_in rin;
rin.sin_family=AF_INET;
rin.sin_port=htons(5555);
rin.sin_addr.s_addr=inet_addr("224.1.2.3");
char wbuf[128]="";
while(1)
{
fgets(wbuf,sizeof(wbuf),stdin);
wbuf[strlen(wbuf)-1]=0;
sendto(sfd,wbuf,strlen(wbuf),0,(struct sockaddr*)&rin,sizeof(rin));
printf("发送成功\n");
if(strcmp(wbuf,"over")==0)
{
break;
}
}
close(sfd);
return 0;
}
int main(int argc, const char *argv[])
{
int rfd=socket(AF_INET,SOCK_DGRAM,0);
if(rfd==-1)
{
perror("sockrt");
return -1;
}
struct sockaddr_in rin;
rin.sin_family=AF_INET;
rin.sin_port=htons(6666);
rin.sin_addr.s_addr=inet_addr("192.168.125.225");
if(bind(rfd,(struct sockaddr*)&rin,sizeof(rin))==-1)
{
perror("bind");
return -1;
}
char rbuf[128]="";
while(1)
{
bzero(rbuf,sizeof(rbuf));
recv(rfd,rbuf,sizeof(rbuf),0);
printf("收到广播:%s\n",rbuf);
if(strcmp(rbuf," OVER ")==0)
{
break;
}
}
close(rfd);
return 0;
}
int main(int argc, const char *argv[])
{
int sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd==-1)
{
perror("socket");
return -1;
}
int res=-1;
int reslen=sizeof(res);
if(getsockopt(sfd,SOL_SOCKET,SO_BROADCAST,&res,&reslen)==-1)
{
perror("getsockopt");
return -1;
}
printf("res=%d\n",res);
int rev=-1;
int revlen=sizeof(rev);
if(setsockopt(sfd,SOL_SOCKET,SO_BROADCAST,&rev,revlen)==-1)
{
perror("setsockopt");
return -1;
}
printf("rev=%d\n",rev);
res=-1;
reslen=sizeof(res);
if(getsockopt(sfd,SOL_SOCKET,SO_BROADCAST,&res,&reslen)==-1)
{
perror("getsockopt");
return -1;
}
printf("res=%d\n",res);
struct sockaddr_in rin;
rin.sin_family=AF_INET;
rin.sin_port=htons(6666);
rin.sin_addr.s_addr=inet_addr("192.168.125.225");
char wbuf[128]="";
while(1)
{
fgets(wbuf,sizeof(wbuf),stdin);
wbuf[strlen(wbuf)]-1==0;
sendto(sfd,wbuf,strlen(wbuf),0,(struct sockaddr*)&rin,sizeof(rin));
printf("发送成功\n");
if(strcmp(wbuf,"over")==0)
{
break;
}
}
close(sfd);
return 0;
}