zoukankan      html  css  js  c++  java
  • 简单的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. 
      

     
  • 相关阅读:
    ASIHTTPRequest系列(一):同步和异步请求
    浅谈SQL Server2005的几种分页方法
    在iphone越狱机器中使用Hook
    iphone4 双击Home键 截获
    xcode中打印毫秒时间
    获得一个不错的电子书翻页效果,和大家分享
    【转】iOS平台XML解析类库对比和安装说明
    xml的sax解析方法
    svn 日常使用技巧以及vim profile的配置
    自制固件iOS4.1刷机、解锁教程
  • 原文地址:https://www.cnblogs.com/helloweworld/p/2709421.html
Copyright © 2011-2022 走看看