最近需要用到网络编程中的广播程序,在网上找了下,亲测可用。
客户端:
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 8 9 int main(void)10 {11 struct sockaddr_in all;12 int fd;13 //广播消息14 char buff[]="this is a broadcast message";15 int so_boradcast=1;16 17 //IPv4 UDP18 fd=socket(AF_INET,SOCK_DGRAM,0);19 //广播地址,用ifconfig查看得到20 all.sin_addr.s_addr=inet_addr("192.168.1.255");21 all.sin_family=AF_INET;22 //端口号23 all.sin_port=htons(8888);24 //设置socket为广播25 setsockopt(fd,SOL_SOCKET,SO_BROADCAST,&so_boradcast,sizeof(so_boradcast));26 27 while(1)28 {29 //广播30 sendto(fd,buff,strlen(buff),0,(struct sockaddr *)&all,sizeof(all));31 //延时1秒32 sleep(1);33 }34 return 0;35 }
服务器端:
1 #include2 #include 3 #include 4 #include 5 6 int main(int argc,char *argv[]) 7 { 8 int fd; 9 struct sockaddr_in server;10 struct sockaddr_in client;11 int status;12 13 //IPv4 UDP14 fd=socket(AF_INET,SOCK_DGRAM,0);15 //端口号16 server.sin_port=htons(8888);17 server.sin_addr.s_addr=INADDR_ANY;18 server.sin_family=AF_INET;19 20 //绑定地址21 status=bind(fd,(struct sockaddr *)&server,sizeof(struct sockaddr));22 if(status<0)23 {24 printf(" bind() error\n");25 exit(1);26 }27 //接收Buffer28 char buff[1024];29 socklen_t len=sizeof(struct sockaddr);30 31 while(1)32 {33 //接收34 recvfrom(fd,buff,1024,0,(struct sockaddr *)&client,&len);35 //打印接收到的信息36 printf("%s\n",buff);37 }38 39 return 0;40 }