How to assign ESP32 static IPv6 address?

After discussing it with Microsoft Copilot for a while we came up with the following solution:

#include <WiFi.h>

#include <esp_event.h>
#include <esp_wifi.h>
#include <esp_netif.h>
#include <lwip/inet.h>
#include <lwip/ip6_addr.h> 
#include <lwip/netif.h>

// Static IPv6 configuration
#define STATIC_IPV6_ADDR "fe80::caf0:9eff:fe2d:f742"

// Function to find the netif structure for a given esp_netif object
static struct netif* get_lwip_netif (esp_netif_t *esp_netif) {
    struct netif *netif = netif_list;
    while (netif != NULL) {
        if (netif->state == esp_netif) {
            return netif;
        }
        netif = netif->next;
    }
    return NULL;
}

void setup () {
    Serial.begin (115200);

    WiFi.begin ("*****", "*****");

    // Configure static IPV6 address
    esp_netif_t *netif = esp_netif_get_handle_from_ifkey ("WIFI_STA_DEF");
    if (netif) {
        // Obtain the lwIP netif from esp_netif
        void *netif_impl = get_lwip_netif (netif);
        if (netif_impl) {
            struct netif *lwip_netif = (struct netif *) netif_impl;
            ip6_addr_t ip6;
            inet6_aton (STATIC_IPV6_ADDR, &ip6);
            netif_ip6_addr_set (lwip_netif, 0, &ip6);
            netif_ip6_addr_set_state (lwip_netif, 0, IP6_ADDR_PREFERRED);

            Serial.printf ("Configured static IPv6 address: %s\n", ip6addr_ntoa (&ip6));
        } else {
            Serial.println ("Failed to get lwIP netif implementation");
        }
    } else {
        Serial.println ("Failed to get netif handle");
    }
}

void loop () {
    
}