|
18 | 18 | #include "freertos/event_groups.h" |
19 | 19 | #include "lwip/err.h" |
20 | 20 | #include "lwip/sys.h" |
| 21 | +#include "lwip/netdb.h" |
21 | 22 |
|
22 | 23 | static const char *TAG = "example_common"; |
23 | 24 |
|
@@ -136,3 +137,46 @@ esp_err_t example_disconnect(void) |
136 | 137 | #endif |
137 | 138 | return ESP_OK; |
138 | 139 | } |
| 140 | + |
| 141 | +esp_err_t example_getaddrinfo(const char *nodename, const char *servname, struct addrinfo **res) |
| 142 | +{ |
| 143 | +#if CONFIG_EXAMPLE_CONNECT_IPV6 |
| 144 | + // Iterate over active interfaces, and find if we have any global scope IPv6 |
| 145 | + bool has_global_scope_ipv6 = false; |
| 146 | + esp_netif_t *netif = NULL; |
| 147 | + while ((netif = esp_netif_next_unsafe(netif)) != NULL) { |
| 148 | + esp_ip6_addr_t ip6[MAX_IP6_ADDRS_PER_NETIF]; |
| 149 | + int ip6_addrs = esp_netif_get_all_ip6(netif, ip6); |
| 150 | + for (int j = 0; j < ip6_addrs; ++j) { |
| 151 | + // Both global and unique local addresses have global scope. |
| 152 | + // ULA assumes either private DNS or NAT66 (same assumpation as IPv4 private address ranges). |
| 153 | + esp_ip6_addr_type_t ipv6_type = esp_netif_ip6_get_addr_type(&(ip6[j])); |
| 154 | + if (ipv6_type == ESP_IP6_ADDR_IS_GLOBAL || ipv6_type == ESP_IP6_ADDR_IS_UNIQUE_LOCAL) { |
| 155 | + has_global_scope_ipv6 = true; |
| 156 | + break; |
| 157 | + } |
| 158 | + } |
| 159 | + if (has_global_scope_ipv6) break; |
| 160 | + } |
| 161 | + |
| 162 | + if (has_global_scope_ipv6) { |
| 163 | + const struct addrinfo hints6 = { |
| 164 | + .ai_family = AF_INET6, |
| 165 | + .ai_socktype = SOCK_STREAM, |
| 166 | + }; |
| 167 | + ESP_LOGI(TAG, "IPv6 DNS lookup"); |
| 168 | + int err6 = getaddrinfo(nodename, servname, &hints6, res); |
| 169 | + if(err6 == 0) return err6; |
| 170 | + ESP_LOGI(TAG, "- IPv6 DNS lookup failed, trying IPv4 lookup"); |
| 171 | + } |
| 172 | +#endif |
| 173 | + |
| 174 | + const struct addrinfo hints4 = { |
| 175 | + .ai_family = AF_INET, |
| 176 | + .ai_socktype = SOCK_STREAM, |
| 177 | + }; |
| 178 | + ESP_LOGI(TAG, "IPv4 DNS lookup"); |
| 179 | + int err4 = getaddrinfo(nodename, servname, &hints4, res); |
| 180 | + |
| 181 | + return err4; |
| 182 | +} |
0 commit comments