arduino-libraries / WiFi

WiFi Library for Arduino
http://arduino.cc/
113 stars 58 forks source link

Make `WiFi.disconnect()` send `DHCPRELEASE` packet #60

Open cxtal opened 1 year ago

cxtal commented 1 year ago

Hi there! I am having some issues with the WiFi library not playing nice with DHCP servers. An illustration would be the following boilerplate logic:

void loop() {
  //...

  WiFi.mode(WIFI_STA);
  WiFi.begin(STA_SSID, STA_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }

  // do

  WiFi.disconnect();

  //...
}

The part after a WiFi disconnect could be a sleep or a very large pause although that is irrelevant.

From the server side it seems that the code would generate the following events:

  1. DHCPDISCOVER
  2. DHCPOFFER
  3. DHCPREQUEST
  4. DHCPACK

which seems fine for requesting an IP but that is rather the end of it and it seems that:

WiFi.disconnect();

is somewhat of a dud in what regards actually shutting down the connection - I have not looked at the code so I am not sure what it does, but it looks like it disconnects the device from WiFi but does not really bother about issuing a DHCPRELEASE in order to let the server know that the IP address currently being held is now free.

I am thinking about crafting a DHCPRELEASE packet myself and sending it through but it would be so much nicer for that to be part of WiFi.disconnect() because it belongs there if WiFi also handles DHCP.

DHCP servers like ISC are clever enough to cache and reuse the same address the next time the same client requests an IP but, pedantically speaking, there is no obligation to cache the client and offer up the same address next time. In case you have quite a large number of IoT devices hammering the DHCP server with requests for IP addresses without even bothering to let the server know that the IP address can be released, this could just shift the workload and power consumption from the client to the server, where the server would just struggle to keep track of all these devices that just abandon their IP addresses and wonder if they'll ever return. Or this behavior could just lead to an IP address starvation attack, by just requesting IP addresses incessantly and hammering the DHCP server with requests.

Would it be alright if we got an RFC1541-compliant implementation for the DHCP part that WiFi handles? Everything is good up and until DHCPACK, flawless, but it would be nice if it could also send a DHCPRELEASE such that DHCP servers can be graciously informed that the IP address can be put back into the address pool.

Thanks!