addr_from_stdin.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include <string.h>
  2. #include "esp_system.h"
  3. #include "esp_log.h"
  4. #include "esp_netif.h"
  5. #include "protocol_examples_common.h"
  6. #include "lwip/sockets.h"
  7. #include <lwip/netdb.h>
  8. #include <arpa/inet.h>
  9. #define HOST_IP_SIZE 128
  10. esp_err_t get_addr_from_stdin(int port, int sock_type, int *ip_protocol, int *addr_family, struct sockaddr_storage *dest_addr)
  11. {
  12. char host_ip[HOST_IP_SIZE];
  13. int len;
  14. static bool already_init = false;
  15. // this function could be called multiple times -> make sure UART init runs only once
  16. if (!already_init) {
  17. example_configure_stdin_stdout();
  18. already_init = true;
  19. }
  20. // ignore empty or LF only string (could receive from DUT class)
  21. do {
  22. fgets(host_ip, HOST_IP_SIZE, stdin);
  23. len = strlen(host_ip);
  24. } while (len<=1 && host_ip[0] == '\n');
  25. host_ip[len - 1] = '\0';
  26. struct addrinfo hints, *addr_list, *cur;
  27. memset( &hints, 0, sizeof( hints ) );
  28. // run getaddrinfo() to decide on the IP protocol
  29. hints.ai_family = AF_UNSPEC;
  30. hints.ai_socktype = sock_type;
  31. hints.ai_protocol = IPPROTO_TCP;
  32. if( getaddrinfo( host_ip, NULL, &hints, &addr_list ) != 0 ) {
  33. return ESP_FAIL;
  34. }
  35. for( cur = addr_list; cur != NULL; cur = cur->ai_next ) {
  36. memcpy(dest_addr, cur->ai_addr, sizeof(*dest_addr));
  37. #if CONFIG_EXAMPLE_CONNECT_IPV4
  38. if (cur->ai_family == AF_INET) {
  39. *ip_protocol = IPPROTO_IP;
  40. *addr_family = AF_INET;
  41. // add port number and return on first IPv4 match
  42. ((struct sockaddr_in*)dest_addr)->sin_port = htons(port);
  43. freeaddrinfo( addr_list );
  44. return ESP_OK;
  45. }
  46. #endif // IPV4
  47. #if CONFIG_EXAMPLE_CONNECT_IPV6
  48. if (cur->ai_family == AF_INET6) {
  49. *ip_protocol = IPPROTO_IPV6;
  50. *addr_family = AF_INET6;
  51. // add port and interface number and return on first IPv6 match
  52. ((struct sockaddr_in6*)dest_addr)->sin6_port = htons(port);
  53. ((struct sockaddr_in6*)dest_addr)->sin6_scope_id = esp_netif_get_netif_impl_index(EXAMPLE_INTERFACE);
  54. freeaddrinfo( addr_list );
  55. return ESP_OK;
  56. }
  57. #endif // IPV6
  58. }
  59. // no match found
  60. freeaddrinfo( addr_list );
  61. return ESP_FAIL;
  62. }