From 9c0c0ce994ab6263316e16a55714e34c9284323e Mon Sep 17 00:00:00 2001 From: zwx Date: Mon, 29 Jul 2024 21:01:49 +0800 Subject: [PATCH] feat(esp_netif): add an API to get all preferred ip6 addresses --- components/esp_netif/include/esp_netif.h | 13 +++++++++++- components/esp_netif/lwip/esp_netif_lwip.c | 24 ++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/components/esp_netif/include/esp_netif.h b/components/esp_netif/include/esp_netif.h index df4beee605..657c6303fa 100644 --- a/components/esp_netif/include/esp_netif.h +++ b/components/esp_netif/include/esp_netif.h @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: 2019-2023 Espressif Systems (Shanghai) CO LTD + * SPDX-FileCopyrightText: 2019-2024 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ @@ -821,6 +821,17 @@ esp_err_t esp_netif_get_ip6_global(esp_netif_t *esp_netif, esp_ip6_addr_t *if_ip * number of returned IPv6 addresses */ int esp_netif_get_all_ip6(esp_netif_t *esp_netif, esp_ip6_addr_t if_ip6[]); + +/** + * @brief Get all preferred IPv6 addresses of the specified interface + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[out] if_ip6 Array of IPv6 addresses will be copied to the argument + * + * @return + * number of returned IPv6 addresses + */ +int esp_netif_get_all_preferred_ip6(esp_netif_t *esp_netif, esp_ip6_addr_t if_ip6[]); #endif /** diff --git a/components/esp_netif/lwip/esp_netif_lwip.c b/components/esp_netif/lwip/esp_netif_lwip.c index 264e214d72..c117daff94 100644 --- a/components/esp_netif/lwip/esp_netif_lwip.c +++ b/components/esp_netif/lwip/esp_netif_lwip.c @@ -2159,6 +2159,30 @@ int esp_netif_get_all_ip6(esp_netif_t *esp_netif, esp_ip6_addr_t if_ip6[]) } return addr_count; } + +int esp_netif_get_all_preferred_ip6(esp_netif_t *esp_netif, esp_ip6_addr_t if_ip6[]) +{ + ESP_LOGV(TAG, "%s esp-netif:%p", __func__, esp_netif); + + if (esp_netif == NULL || if_ip6 == NULL) { + return 0; + } + + int addr_count = 0; + struct netif *p_netif = esp_netif->lwip_netif; + + if (p_netif != NULL && netif_is_up(p_netif)) { + for (int i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++) { + // Only return the IPs which are: + // 1. the state is preferred + // 2. not the IP6_ADDR_ANY(all bits are `0`) + if (ip6_addr_ispreferred(netif_ip6_addr_state(p_netif, i)) && !ip_addr_cmp(&p_netif->ip6_addr[i], IP6_ADDR_ANY)) { + memcpy(&if_ip6[addr_count++], &p_netif->ip6_addr[i], sizeof(ip6_addr_t)); + } + } + } + return addr_count; +} #endif esp_netif_flags_t esp_netif_get_flags(esp_netif_t *esp_netif)