From c6a8da61f78452573df857cb95edb3a5ecd0365f Mon Sep 17 00:00:00 2001 From: ahorn42 Date: Fri, 6 Nov 2020 13:16:50 +0100 Subject: [PATCH] Allow faster reuse of socket, to be able to restart WifiServer. (#4306) See #3960 for more details of the problem and the solution. I only implemented what was proposed in this ticket, as it solves my problem, which was the same as in this ticket. Credits for the code going to @etrinh ;-) This also is a more consistence behaviour compared to esp8266, where it also is possible to restart the wifiserver immediately on the same port. --- libraries/WiFi/src/WiFiServer.cpp | 5 +++++ libraries/WiFi/src/WiFiServer.h | 1 + 2 files changed, 6 insertions(+) diff --git a/libraries/WiFi/src/WiFiServer.cpp b/libraries/WiFi/src/WiFiServer.cpp index 75c2872b..d6a5ae82 100644 --- a/libraries/WiFi/src/WiFiServer.cpp +++ b/libraries/WiFi/src/WiFiServer.cpp @@ -63,6 +63,10 @@ WiFiClient WiFiServer::available(){ } void WiFiServer::begin(uint16_t port){ + begin(port, 1); +} + +void WiFiServer::begin(uint16_t port, int enable){ if(_listening) return; if(port){ @@ -72,6 +76,7 @@ void WiFiServer::begin(uint16_t port){ sockfd = socket(AF_INET , SOCK_STREAM, 0); if (sockfd < 0) return; + setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)); server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(_port); diff --git a/libraries/WiFi/src/WiFiServer.h b/libraries/WiFi/src/WiFiServer.h index 34952cc6..aeb831db 100644 --- a/libraries/WiFi/src/WiFiServer.h +++ b/libraries/WiFi/src/WiFiServer.h @@ -40,6 +40,7 @@ class WiFiServer : public Server { WiFiClient available(); WiFiClient accept(){return available();} void begin(uint16_t port=0); + void begin(uint16_t port, int reuse_enable); void setNoDelay(bool nodelay); bool getNoDelay(); bool hasClient();