broadsend.c
#include<myhead.h>
#define boardIP "192.168.0.255"
#define boardPort 9999
int main(int argc, const char *argv[])
{
//1.socket
int boardsocket = socket(AF_INET,SOCK_DGRAM,0);
if(boardsocket==-1)
{
perror("boardsocket");
return -1;
}
//2.setsockopt
int k = 1;
if(setsockopt(boardsocket,SOL_SOCKET,SO_BROADCAST,&k,sizeof(k))==-1)
{
perror("setsockopt");
return -1;
}
struct sockaddr_in snd={
.sin_family = AF_INET,
.sin_addr = inet_addr(boardIP),
.sin_port = htons(boardPort)
};
//3.sendto
char buff[1024];
while(1)
{
printf("广播通知:\n");
fgets(buff,sizeof(buff),stdin);
sendto(boardsocket,buff,sizeof(buff),0,(struct sockaddr*)&snd,sizeof(snd));
printf("发送成功\n");
}
//4、close
close(boardsocket);
return 0;
}
broadrev.c
#include<myhead.h>
#define boardIP "192.168.0.255"
#define boardPort 9999
int main(int argc, const char *argv[])
{
//1.socket
int boardsocket = socket(AF_INET,SOCK_DGRAM,0);
if(boardsocket==-1)
{
perror("boardsocket");
return -1;
}
//2.bind
struct sockaddr_in rev={
.sin_family = AF_INET,
.sin_addr = inet_addr(boardIP),
.sin_port = htons(boardPort)
};
if(bind(boardsocket,(struct sockaddr*)&rev,sizeof(rev))==-1)
{
perror("bind");
return -1;
}
//struct sockaddr_in snd;
// int sndlen =sizeof(snd);
char buff[1024];
while(1)
{
memset(buff,0,sizeof(buff));
recvfrom(boardsocket,buff,sizeof(buff),0,NULL,NULL);
printf("%s\n",buff);
}
close(boardsocket);
return 0;
}