广播机制的CS模型实现
广播机制的cs模型实现如下:
首先可以使用ifconfig命令查看自己所在网段的广播地址
server.c
1 #include<stdio.h> 2 #include<unistd.h> 3 #include<stdlib.h> 4 #include <strings.h> 5 #include<string.h> 6 #include<sys/socket.h> 7 #include<arpa/inet.h> 8 #include<net/if.h> 9 10 #define SERVER_PORT 8000 //服务端端口无关紧要 11 #define MAXLINE 1500 12 13 #define BROADCAST_IP "192.168.23.255"//所在局域网的广播IP 14 #define CLIENT_PORT 9000 //客户端端口必须指定 15 16 int main(int argc,char* argv[]) 17 { 18 int sockfd; 19 struct sockaddr_in servaddr,clieaddr; 20 char buf[MAXLINE]; 21 //构造用于UDP通信的套接字 22 sockfd = socket(AF_INET,SOCK_DGRAM,0); 23 24 bzero(&servaddr,sizeof(servaddr)); 25 servaddr.sin_family = AF_INET; //IPv4 26 servaddr.sin_addr.s_addr = htonl(INADDR_ANY);//本地任意有效IP 27 servaddr.sin_port = htons(SERVER_PORT); 28 29 bind(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); 30 31 int flag = 1; 32 setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,&flag,sizeof(flag)); 33 34 //构造client地址 IP+端口 35 bzero(&clieaddr,sizeof(clieaddr)); 36 clieaddr.sin_family = AF_INET; 37 inet_pton(AF_INET,BROADCAST_IP,&clieaddr.sin_addr.s_addr); 38 clieaddr.sin_port = htons(CLIENT_PORT); 39 40 int i = 0; 41 while(1) 42 { 43 sprintf(buf,"服务端发送了广播%d 次\n",i++); 44 sendto(sockfd,buf,strlen(buf),0,(struct sockaddr*)&clieaddr,sizeof(clieaddr)); 45 sleep(1); 46 } 47 close(sockfd); 48 49 return 0; 50 }
client.c
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<strings.h> 4 #include<string.h> 5 #include<sys/socket.h> 6 #include<unistd.h> 7 #include<sys/types.h> 8 #include<arpa/inet.h> 9 10 #define SERVER_PORT 8000 11 #define CLIENT_PORT 9000 12 #define MAXLINE 4096 13 14 int main(int argc,char* argv[]) 15 { 16 struct sockaddr_in localaddr; 17 int confd; 18 ssize_t len; 19 char buf[MAXLINE]; 20 //1.创建一个socket 21 confd = socket(AF_INET,SOCK_DGRAM,0); 22 //初始化本地地址 23 bzero(&localaddr,sizeof(localaddr)); 24 localaddr.sin_family = AF_INET; 25 inet_pton(AF_INET,"0.0.0.0",&localaddr.sin_addr.s_addr); 26 localaddr.sin_port = htons(CLIENT_PORT); 27 28 int ret = bind(confd,(struct sockaddr*)&localaddr,sizeof(localaddr)); 29 if(ret == 0) 30 { 31 printf("...bind ok...\n"); 32 } 33 while(1) 34 { 35 len = recvfrom(confd,buf,sizeof(buf),0,NULL,0); 36 write(STDOUT_FILENO,buf,len); 37 } 38 close(confd); 39 40 return 0; 41 }
测试结果:
努力不一定有结果,有结果不一定是努力