服务器端:

 
  
  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <unistd.h> 
  4. #include <sys/socket.h> 
  5. #include <netinet/in.h> 
  6. #include <string.h> 
  7. #include <pthread.h> 
  8.  
  9.  
  10. int main()//service code 
  11.     int fd; 
  12.     int sockfd; 
  13.      
  14.     struct sockaddr_in myaddr, clientaddr; 
  15.      
  16.     char buf[100]=""; 
  17.     int len = sizeof(clientaddr); 
  18.     bzero(&clientaddr, sizeof(clientaddr)); 
  19.     bzero(&myaddr, sizeof(myaddr)); 
  20.     myaddr.sin_family = AF_INET
  21.     myaddr.sin_port = htons(2222); 
  22.     myaddr.sin_addr.s_addr = inet_addr("127.0.0.1");//设定本机的回环地址 
  23.      
  24.     if((sockfd = socket(AF_INET, SOCK_DGRAM, 0))<0
  25.     { 
  26.         perror("socket"); 
  27.         exit(1);     
  28.     } 
  29.      
  30.     if(bind(sockfd, (struct sockaddr*)&myaddr, sizeof(struct sockaddr))!=0) 
  31.     { 
  32.         perror("bind"); 
  33.         exit(1);     
  34.     } 
  35.      
  36.     recvfrom(sockfd, buf, 100, 0, (struct sockaddr*)&clientaddr, &len); 
  37.     printf("recv:%s\n",buf); 
  38.     sendto(sockfd, "OK!", 3, 0, (struct sockaddr*)&clientaddr, len); 
  39.  
  40.     return fd; 
  41.  

客户端:

 
  
  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <unistd.h> 
  4. #include <sys/socket.h> 
  5. #include <netinet/in.h> 
  6. #include <string.h> 
  7. #include <pthread.h> 
  8.  
  9.  
  10. int main()//client code 
  11.     int fd; 
  12.     int sockfd; 
  13.      
  14.     struct sockaddr_in myaddr, clientaddr; 
  15.      
  16.     char buf[100]=""; 
  17.     int len = sizeof(clientaddr); 
  18.     bzero(&clientaddr, sizeof(clientaddr)); 
  19.     bzero(&myaddr, sizeof(myaddr)); 
  20.     myaddr.sin_family = AF_INET
  21.     myaddr.sin_port = htons(2222); 
  22.     myaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); 
  23.      
  24.     if((sockfd = socket(AF_INET, SOCK_DGRAM, 0))<0
  25.     { 
  26.         perror("socket"); 
  27.         exit(1);     
  28.     } 
  29.      
  30.     sendto(sockfd, "hello!", 10, 0, (struct sockaddr*)&myaddr, len); 
  31.      
  32.     recvfrom(sockfd, buf, 100, 0, (struct sockaddr*)&myaddr, &len); 
  33.     printf("recv:%s\n",buf); 
  34.      
  35.  
  36.     return fd;