简单的UDP套接字编程例子

UDP系统调用时序图

image

简单的UDP例子

 

隐藏行号 复制代码 server
  1. /*
    
  2.  ============================================================================
    
  3.  Name        : UDPserver.c
    
  4.  Author      : vestinfo
    
  5.  Version     : 1.1
    
  6.  Copyright   : Your copyright notice
    
  7.  Description : A simple UDP server, Ansi-style
    
  8.  ============================================================================
    
  9.  */
    
  10. 
    
  11. #include <stdio.h>
    
  12. #include <stdlib.h>
    
  13. #include <string.h>
    
  14. #include <netinet/in.h>
    
  15. #include <arpa/inet.h>
    
  16. #include <unistd.h>
    
  17. #include <sys/stat.h>
    
  18. #include <sys/types.h>
    
  19. #include <sys/socket.h>
    
  20. 
    
  21. #define LOCALPORT 8888
    
  22. 
    
  23. int main(int argc,char *argv[])
    
  24. {
    
  25. int sockfd;
    
  26. struct sockaddr_in addr;
    
  27. char msg[256];
    
  28. int addr_len;
    
  29. 
    
  30. if((sockfd=socket(AF_INET,SOCK_DGRAM,0)) < 0)
    
  31.     {
    
  32. perror("error");
    
  33. exit(1);
    
  34.     }
    
  35. 
    
  36.     addr_len=sizeof(struct sockaddr);
    
  37. bzero(&addr,sizeof(addr));
    
  38.     addr.sin_family = AF_INET;
    
  39.     addr.sin_port = htons(LOCALPORT);
    
  40.     addr.sin_addr.s_addr = htonl(INADDR_ANY);
    
  41. 
    
  42. if(bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    
  43.     {
    
  44. perror("error");
    
  45. exit(1);
    
  46.     }
    
  47. 
    
  48. printf("UDP server waiting for client...\n");
    
  49. 
    
  50. while(1)
    
  51.     {
    
  52. bzero(msg,sizeof(msg));
    
  53. recvfrom(sockfd,msg,sizeof(msg),0,(struct sockaddr *)&addr,&addr_len);
    
  54. 
    
  55. printf("Received message from:%s\n",inet_ntoa(addr.sin_addr));
    
  56. printf("The message Received from client:%s",msg);
    
  57. 
    
  58. sendto(sockfd,msg,sizeof(msg),0,(struct sockaddr *)&addr,addr_len);
    
  59.     }
    
  60. }
    
  61. 
    

 

 
posted @ 2012-09-30 22:43  helloweworld  阅读(1129)  评论(0编辑  收藏  举报