]> granicus.if.org Git - esp-idf/commitdiff
esp_http_server : Allow binding to same address and port upon restarting server witho...
authorAnurag Kar <anurag.kar@espressif.com>
Mon, 29 Apr 2019 13:16:20 +0000 (18:46 +0530)
committerbot <bot@espressif.com>
Thu, 2 May 2019 05:29:38 +0000 (05:29 +0000)
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

index d499708381045be24a71e03646a34e9c2da0a522..8d5e9eef9b94f7e71111154d7366343969e10d5e 100644 (file)
@@ -254,6 +254,15 @@ static esp_err_t httpd_server_init(struct httpd_data *hd)
         .sin6_port    = htons(hd->config.server_port)
     };
 
+    /* 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 enabling 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);