From 0d9450ea0066d5a7a84548c296f500d63fe2fc71 Mon Sep 17 00:00:00 2001 From: Chen Wu Date: Fri, 5 May 2023 17:44:59 +0800 Subject: [PATCH] feat(httpd): Allow binding to same address and port upon restarting server without delay Issue : Restarting the server without 30sec delay between httpd_stop() and httpd_start() causes EADDRINUSE error Resolution : Use setsockopt() to enable SO_REUSEADDR on listener socket Closes https://github.com/espressif/esp-idf/issues/3381 --- components/esp_http_server/src/httpd_main.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/components/esp_http_server/src/httpd_main.c b/components/esp_http_server/src/httpd_main.c index a6751319..5724383a 100644 --- a/components/esp_http_server/src/httpd_main.c +++ b/components/esp_http_server/src/httpd_main.c @@ -262,6 +262,16 @@ static esp_err_t httpd_server_init(struct httpd_data *hd) .sin_port = htons(hd->config.server_port) }; #endif /* CONFIG_LWIP_IPV6 */ + + /* Enable SO_REUSEADDR to allow binding to the same + * address and port when restarting the server */ + int enable = 1; + if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) < 0) { + /* This will fail if CONFIG_LWIP_SO_REUSE is not enabled. But + * it does not affect the normal working of the HTTP Server */ + ESP_LOGW(TAG, LOG_FMT("error in setsockopt SO_REUSEADDR (%d)"), errno); + } + int ret = bind(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); if (ret < 0) { ESP_LOGE(TAG, LOG_FMT("error in bind (%d)"), errno);