当前位置:   article > 正文

c语言实现简单的tcp客户端_srckf 程序

srckf 程序

功能:实现一个简单的tcp客户端,连接本地端口8888的tcp服务端,并发送一条报文。
 

  1. /*
  2. * File: main.c
  3. * Author: vincent
  4. *
  5. * Created on 2023年8月3日, 上午9:56
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <unistd.h>
  11. #include <sys/socket.h>
  12. #include <netinet/in.h>
  13. #include <arpa/inet.h>
  14. #include <pthread.h>
  15. #define TARGET_PORT 8888
  16. #define TARGET_IP "127.0.0.1"
  17. /*
  18. *
  19. */
  20. int main(int argc, char** argv)
  21. {
  22. int ret = 1;
  23. int i;
  24. unsigned char recv_buff[1024] = {0};
  25. int read_len = 0;
  26. int send_len = 0;
  27. unsigned char *send_data = "hello,this is a tcp client\n";
  28. //创建套接字
  29. int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
  30. if (socket_fd < 0)
  31. {
  32. printf("socket err\n");
  33. return -1;
  34. }
  35. printf("socket create success sfd=%d\n", socket_fd);
  36. struct sockaddr_in dest;
  37. socklen_t len = sizeof (dest);
  38. dest.sin_family = AF_INET;
  39. dest.sin_port = htons(TARGET_PORT);
  40. dest.sin_addr.s_addr = inet_addr(TARGET_IP);
  41. ret = connect(socket_fd, (const struct sockaddr *) &dest, len);
  42. if (ret < 0)
  43. {
  44. perror("connect");
  45. close(socket_fd);
  46. socket_fd = -1;
  47. return -1;
  48. }
  49. send_len = send(socket_fd, send_data, strlen(send_data), 0);
  50. if (send_len <= 0)
  51. {
  52. printf("send err\n");
  53. close(socket_fd);
  54. socket_fd = -1;
  55. return -1;
  56. }
  57. memset(recv_buff, 0x00, sizeof (recv_buff));
  58. read_len = recv(socket_fd, recv_buff, sizeof (recv_buff), 0);
  59. if (read_len < 0)
  60. {
  61. printf("recv err\n");
  62. close(socket_fd);
  63. socket_fd = -1;
  64. return -1;
  65. } else if (read_len == 0)
  66. {
  67. printf("close \n");
  68. close(socket_fd);
  69. socket_fd = -1;
  70. return -1;
  71. }
  72. printf("recv data: %s\n", recv_buff);
  73. // for (i = 0; i < read_len; i++)
  74. // {
  75. // printf("%02x ", recv_buff[i]);
  76. // }
  77. // printf("\n");
  78. close(socket_fd);
  79. socket_fd = -1;
  80. return (EXIT_SUCCESS);
  81. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/144104
推荐阅读
相关标签
  

闽ICP备14008679号