• 简单的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. 
      

     
  • 相关阅读:
    从三道题目入门frida
    APP 抓包(应用层)
    安卓开发--探究碎片Fragment
    centos7-查询内存/硬盘等详细信息
    网页视频下载神器
    error: C++ preprocessor "/lib/cpp" fails sanity check错误解决方法
    make源文件时出现 /usr/bin/ld: cannot find -lstdc++ 错误
    安装docker后修改docker文件目录
    centos集群中各节点如何实现时间同步?
    redhat7.5 yum不能用
  • 原文地址:https://www.cnblogs.com/helloweworld/p/2709421.html
Copyright © 2020-2023  润新知