标签:
实验目的:
熟悉基本UDP套接字编程流程(服务器、客户端)
掌握流程中的关键函数的用法
实验内容:
服务器
1 #include<stdio.h> 2 #include<string.h> 3 #include<unistd.h> 4 #include<sys/types.h> 5 #include<sys/socket.h> 6 #include<stdlib.h> 7 #include<netinet/in.h> 8 #include<arpa/inet.h> 9 #define PORT 1234 10 #define MAXDATASIZE 100 11 main() 12 { 13 int sockfd; 14 struct sockaddr_in server; 15 struct sockaddr_in client; 16 socklen_t len; 17 int num; 18 char buf[MAXDATASIZE]; 19 if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 20 { 21 perror("Creating socket failed"); 22 exit(1); 23 } 24 bzero(&server,sizeof(server)); 25 server.sin_family=AF_INET; 26 server.sin_port=htons(PORT); 27 server.sin_addr.s_addr = htonl(INADDR_ANY); 28 if(bind(sockfd, (struct sockaddr *)&server, sizeof(server)) == -1) 29 { 30 perror("Bind() error."); 31 exit(1); 32 } 33 len=sizeof(client); 34 while(1) 35 { 36 num = recvfrom(sockfd,buf,MAXDATASIZE,0,(struct sockaddr *)&client,&len); 37 if ( num<0) 38 { 39 perror("recvfrom() error\n"); 40 exit(1); 41 } 42 buf[num] = ‘\0‘; 43 printf("You got a message <%s> from cient.\nIt‘s ip is %s, port is %d.\n",buf,inet_ntoa(client.sin_addr),htons(client.sin_port)); 44 sendto(sockfd,"Welcome\n",8,0,(struct sockaddr *)&client,len); 45 if(!strcmp(buf,"bye")) 46 break; 47 } 48 close(sockfd); 49 }
客户端:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<unistd.h> 4 #include<string.h> 5 #include<sys/types.h> 6 #include<sys/socket.h> 7 #include<netinet/in.h> 8 #include<netdb.h> 9 #define PORT 1234 10 #define MAXDATASIZE 100 11 int main(int argc, char *argv[]) 12 { 13 int sockfd, num; 14 char buf[MAXDATASIZE]; 15 struct hostent *he; 16 struct sockaddr_in server,peer; 17 if (argc !=3) 18 { 19 printf("Usage: %s <IP Address> <message>\n",argv[0]); 20 exit(1); 21 } 22 if ((he=gethostbyname(argv[1]))==NULL) 23 { 24 printf("gethostname() error\n"); 25 exit(1); 26 } 27 if ((sockfd=socket(AF_INET, SOCK_DGRAM, 0))==-1) 28 { 29 printf("socket() error\n"); 30 exit(1); 31 } 32 bzero(&server,sizeof(server)); 33 server.sin_family = AF_INET; 34 server.sin_port = htons(PORT); 35 server.sin_addr =* ((struct in_addr *)he->h_addr); 36 sendto(sockfd, argv[2], strlen(argv[2]), 0 , (struct sockaddr *)&server, sizeof(server)); 37 socklen_t len; 38 len=sizeof(server); 39 while(1) 40 { 41 if((num=recvfrom(sockfd,buf,MAXDATASIZE,0,(struct sockaddr *)&peer,&len)) == -1) 42 { 43 printf("recvfrom() error\n"); 44 exit(1); 45 } 46 if(len !=sizeof(server) || memcmp((const void *)&server, (const void *) &peer,len) !=0) 47 { 48 printf("Rcecive message from other server.\n"); 49 continue; 50 } 51 buf[num]=‘\0‘; 52 printf("Server Message: %s",buf); 53 break; 54 } 55 close(sockfd); 56 }
标签:
原文地址:http://www.cnblogs.com/elewei/p/4770324.html