How to set WiFi DHCP hostname on ESP32/ESP8266 (different from "espressif")

Using ESP-IDF

ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_t* wifiStaNetif = esp_netif_create_default_wifi_sta();

const char* hostname = "MyESP32";
ESP_ERROR_CHECK(esp_netif_set_hostname(wifiStaNetif, hostname));

Using Arduino framework

Use

WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
WiFi.setHostname("My-ESP32-Test");

to set a custom hostname for the ESP32. TheĀ Wifi.config(...) line is required as a workaround for this bug on Github.