tcp_client_v4.c 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Unlicense OR CC0-1.0
  5. */
  6. #include "sdkconfig.h"
  7. #include <string.h>
  8. #include <unistd.h>
  9. #include <sys/socket.h>
  10. #include <errno.h>
  11. #include <netdb.h> // struct addrinfo
  12. #include <arpa/inet.h>
  13. #include "esp_netif.h"
  14. #include "esp_log.h"
  15. #if defined(CONFIG_EXAMPLE_SOCKET_IP_INPUT_STDIN)
  16. #include "addr_from_stdin.h"
  17. #endif
  18. #if defined(CONFIG_EXAMPLE_IPV4)
  19. #define HOST_IP_ADDR CONFIG_EXAMPLE_IPV4_ADDR
  20. #elif defined(CONFIG_EXAMPLE_SOCKET_IP_INPUT_STDIN)
  21. #define HOST_IP_ADDR ""
  22. #endif
  23. #define PORT CONFIG_EXAMPLE_PORT
  24. static const char *TAG = "example";
  25. static const char *payload = "Message from ESP32 ";
  26. void tcp_client(void)
  27. {
  28. char rx_buffer[128];
  29. char host_ip[] = HOST_IP_ADDR;
  30. int addr_family = 0;
  31. int ip_protocol = 0;
  32. while (1) {
  33. #if defined(CONFIG_EXAMPLE_IPV4)
  34. struct sockaddr_in dest_addr;
  35. inet_pton(AF_INET, host_ip, &dest_addr.sin_addr);
  36. dest_addr.sin_family = AF_INET;
  37. dest_addr.sin_port = htons(PORT);
  38. addr_family = AF_INET;
  39. ip_protocol = IPPROTO_IP;
  40. #elif defined(CONFIG_EXAMPLE_SOCKET_IP_INPUT_STDIN)
  41. struct sockaddr_storage dest_addr = { 0 };
  42. ESP_ERROR_CHECK(get_addr_from_stdin(PORT, SOCK_STREAM, &ip_protocol, &addr_family, &dest_addr));
  43. #endif
  44. int sock = socket(addr_family, SOCK_STREAM, ip_protocol);
  45. if (sock < 0) {
  46. ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
  47. break;
  48. }
  49. ESP_LOGI(TAG, "Socket created, connecting to %s:%d", host_ip, PORT);
  50. int err = connect(sock, (struct sockaddr *)&dest_addr, sizeof(dest_addr));
  51. if (err != 0) {
  52. ESP_LOGE(TAG, "Socket unable to connect: errno %d", errno);
  53. break;
  54. }
  55. ESP_LOGI(TAG, "Successfully connected");
  56. while (1) {
  57. int err = send(sock, payload, strlen(payload), 0);
  58. if (err < 0) {
  59. ESP_LOGE(TAG, "Error occurred during sending: errno %d", errno);
  60. break;
  61. }
  62. int len = recv(sock, rx_buffer, sizeof(rx_buffer) - 1, 0);
  63. // Error occurred during receiving
  64. if (len < 0) {
  65. ESP_LOGE(TAG, "recv failed: errno %d", errno);
  66. break;
  67. }
  68. // Data received
  69. else {
  70. rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string
  71. ESP_LOGI(TAG, "Received %d bytes from %s:", len, host_ip);
  72. ESP_LOGI(TAG, "%s", rx_buffer);
  73. }
  74. }
  75. if (sock != -1) {
  76. ESP_LOGE(TAG, "Shutting down socket and restarting...");
  77. shutdown(sock, 0);
  78. close(sock);
  79. }
  80. }
  81. }