addr_from_stdin.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 (cur->ai_family == AF_INET) {
  38. *ip_protocol = IPPROTO_IP;
  39. *addr_family = AF_INET;
  40. // add port number and return on first IPv4 match
  41. ((struct sockaddr_in*)dest_addr)->sin_port = htons(port);
  42. freeaddrinfo( addr_list );
  43. return ESP_OK;
  44. }
  45. #if CONFIG_LWIP_IPV6
  46. else if (cur->ai_family == AF_INET6) {
  47. *ip_protocol = IPPROTO_IPV6;
  48. *addr_family = AF_INET6;
  49. // add port and interface number and return on first IPv6 match
  50. ((struct sockaddr_in6*)dest_addr)->sin6_port = htons(port);
  51. ((struct sockaddr_in6*)dest_addr)->sin6_scope_id = esp_netif_get_netif_impl_index(EXAMPLE_INTERFACE);
  52. freeaddrinfo( addr_list );
  53. return ESP_OK;
  54. }
  55. #endif
  56. }
  57. // no match found
  58. freeaddrinfo( addr_list );
  59. return ESP_FAIL;
  60. }