最近需要用到网络编程中的广播程序,在网上找了下,亲测可用。
客户端:
1 #include <stdio.h> 2 #include <arpa/inet.h> 3 #include <string.h> 4 #include <sys/ioctl.h> 5 #include <net/if.h> 6 #include <unistd.h> 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 UDP 18 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 #include <stdio.h> 2 #include <arpa/inet.h> 3 #include <stdlib.h> 4 #include <unistd.h> 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 UDP 14 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 //接收Buffer 28 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 }