千家信息网

unix 网络编程udp简单例程

发表于:2025-01-26 作者:千家信息网编辑
千家信息网最后更新 2025年01月26日,server.c#include /* See NOTES */#include #include #include #include #include #include #includ
千家信息网最后更新 2025年01月26日unix 网络编程udp简单例程
  1. server.c
  2. #include <sys/types.h> /* See NOTES */
  3. #include <sys/socket.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <stdio.h>
  8. #include <arpa/inet.h>
  9. #include <unistd.h>
  10. int main(int argc, char** argv)
  11. {
  12. int ret;
  13. int len = sizeof(struct sockaddr);
  14. //创建socket
  15. int sockfd = socket(AF_INET, SOCK_DGRAM,0);
  16. if(sockfd == -1)
  17. {
  18. perror("socket\n");
  19. exit(1);
  20. }
  21. //将addr地址与socket绑定在一起
  22. //初始化地址
  23. struct sockaddr_in addr;
  24. addr.sin_family = AF_INET;
  25. addr.sin_port = htons(4444);
  26. addr.sin_addr.s_addr = INADDR_ANY;
  27. memset(addr.sin_zero,8,0);
  28. //进行绑定
  29. ret = bind(sockfd, (struct sockaddr*)&addr, len);
  30. if(ret == -1)
  31. {
  32. perror("bind\n");
  33. exit(1);
  34. }
  35. //接收数据
  36. struct sockaddr_in addr_client;
  37. while(1)
  38. {
  39. char buf[100];
  40. memset(buf,100,0);
  41. socklen_t length = sizeof(struct sockaddr);
  42. fputs("等待数据。。。。\n",stdout);
  43. ssize_t recnum = recvfrom(sockfd, buf, 100,MSG_WAITALL, (struct sockaddr*)&addr_client,&length);
  44. if(recnum<0)
  45. {
  46. perror("recvfrom\n");
  47. exit(1);
  48. }
  49. printf("received(%d): %s\n",recnum,buf);
  50. if(strcmp(buf,"stop") == 0)
  51. {
  52. break;
  53. }
  54. }
  55. close(sockfd);
  56. fputs("退出成功!!\n",stdout);
  57. return 0;
  58. }
  59. ----------------------------
  60. client.c
  61. #include <sys/types.h> /* See NOTES */
  62. #include <sys/socket.h>
  63. #include <stdio.h>
  64. #include <stdlib.h>
  65. #include <string.h>
  66. #include <stdio.h>
  67. #include <arpa/inet.h>
  68. #include <unistd.h>
  69. int main(int argc, char** argv)
  70. {
  71. int len = sizeof(struct sockaddr);
  72. //创建socket
  73. int sockfd = socket(AF_INET, SOCK_DGRAM,0);
  74. if(sockfd == -1)
  75. {
  76. perror("socket\n");
  77. exit(1);
  78. }
  79. //将addr地址与socket绑定在一起
  80. //初始化地址
  81. struct sockaddr_in addr;
  82. addr.sin_family = AF_INET;
  83. addr.sin_port = htons(4444);
  84. addr.sin_addr.s_addr = inet_addr("127.0.0.1");
  85. memset(addr.sin_zero,8,0);
  86. while(1)
  87. {
  88. char buf[100];
  89. memset(buf,100,0);
  90. fputs("请输入内容:\n",stdout);
  91. //存在scanf字符串空格问题
  92. scanf("%s",buf);
  93. fputs("确认发送内容为:\n",stdout);
  94. fputs(buf,stdout);
  95. printf("\n");
  96. sendto(sockfd, buf, 100, 0, (struct sockaddr*)&addr, len);
  97. fputs("确认发送完成\n",stdout);
  98. }
  99. return 0;
  100. }
  101. ----------------------------
  102. makefile
  103. .PHONY: all clean
  104. all:server client
  105. server:server.c
  106. gcc -o server server.c -Wall
  107. client:client.c
  108. gcc -o client client.c -Wall
  109. clean:
  110. rm -f *.o client server *~
0