Search code examples
tcptcpclientmicropythonesp32

ESP32 TCP client


I want to set up TCP server on windows and TCP client on ESP32. Main idea is to send String to ESP32 change it and send it back to server, but I'm really new with all of this stuff and got stuck on setting up TCP client on ESP32. Examples or references would be really helpful.


Solution

  • int create_ipv4_socket()
    {
      struct addrinfo hints;
      struct addrinfo *res;
      struct in_addr *addr;
    
      hints.ai_family = AF_INET;
      hints.ai_socktype = SOCK_STREAM;
    
      int err = getaddrinfo(UDP_IPV4_ADDR, TCP_PORT, &hints, &res);
    
      if(err != 0 || res == NULL) {
        printf("DNS lookup failed err=%d res=%p\n", err, res);
        return -1;
      }
    
      /* Code to print the resolved IP.
    
         Note: inet_ntoa is non-reentrant, look at ipaddr_ntoa_r for "real" code */
      addr = &((struct sockaddr_in *)res->ai_addr)->sin_addr;
      printf("DNS lookup succeeded. IP=%s\n", inet_ntoa(*addr));
    
      l_sock = socket(res->ai_family, res->ai_socktype, 0);
      if(l_sock < 0) {
        printf("... Failed to allocate socket.\n");
        freeaddrinfo(res);
        return -1;
      }
    
      struct timeval to;
      to.tv_sec = 2;
      to.tv_usec = 0;
      setsockopt(l_sock,SOL_SOCKET,SO_SNDTIMEO,&to,sizeof(to));
    
      if(connect(l_sock, res->ai_addr, res->ai_addrlen) != 0) {
        printf("... socket connect failed errno=%d\n", errno);
        close(l_sock);
        freeaddrinfo(res);
        return -1;
      }
    
      printf("... connected\n");
      freeaddrinfo(res);
    
      // All set, socket is configured for sending and receiving
      return l_sock;
    }
    

    From this forum https://www.esp32.com/viewtopic.php?t=5965