Skip to content

Commit 4aa2f24

Browse files
committed
feat(ap): Add support for DHCP Captive Portal (opt 114)
1 parent 72a582b commit 4aa2f24

File tree

3 files changed

+46
-2
lines changed

3 files changed

+46
-2
lines changed

libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,9 @@ void handleNotFound() {
3434

3535
void setup() {
3636
Serial.begin(115200);
37-
WiFi.mode(WIFI_AP);
38-
WiFi.softAP("ESP32-DNSServer");
37+
WiFi.AP.begin();
38+
WiFi.AP.create("ESP32-DNSServer");
39+
WiFi.AP.enableDhcpCaptivePortal();
3940

4041
// by default DNSServer is started serving any "*" domain name. It will reply
4142
// AccessPoint's IP to all DNS request (this is required for Captive Portal detection)

libraries/WiFi/src/AP.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,48 @@ bool APClass::enableNAPT(bool enable) {
305305
return true;
306306
}
307307

308+
bool APClass::enableDhcpCaptivePortal() {
309+
#if CONFIG_ESP_ENABLE_DHCP_CAPTIVEPORTAL
310+
esp_err_t err = ESP_OK;
311+
static char captiveportal_uri[32] = {0,};
312+
313+
if (!started()) {
314+
log_e("AP must be first started to enable DHCP Captive Portal");
315+
return false;
316+
}
317+
318+
// Create Captive Portal URL: http://192.168.0.4
319+
strcpy(captiveportal_uri, "http://");
320+
strcat(captiveportal_uri, String(localIP()).c_str());
321+
322+
// Stop DHCPS
323+
err = esp_netif_dhcps_stop(_esp_netif);
324+
if (err && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
325+
log_e("DHCPS Stop Failed! 0x%04x: %s", err, esp_err_to_name(err));
326+
return false;
327+
}
328+
329+
// Enable DHCP Captive Portal
330+
err = esp_netif_dhcps_option(_esp_netif, ESP_NETIF_OP_SET, ESP_NETIF_CAPTIVEPORTAL_URI, captiveportal_uri, strlen(captiveportal_uri));
331+
if (err) {
332+
log_e("Could not set enable DHCP Captive Portal! 0x%x: %s", err, esp_err_to_name(err));
333+
return false;
334+
}
335+
336+
// Start DHCPS
337+
err = esp_netif_dhcps_start(_esp_netif);
338+
if (err) {
339+
log_e("DHCPS Start Failed! 0x%04x: %s", err, esp_err_to_name(err));
340+
return false;
341+
}
342+
343+
return true;
344+
#else
345+
log_e("CONFIG_ESP_ENABLE_DHCP_CAPTIVEPORTAL is not enabled!");
346+
return false;
347+
#endif
348+
}
349+
308350
String APClass::SSID(void) const {
309351
if (!started()) {
310352
return String();

libraries/WiFi/src/WiFiAP.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ class APClass : public NetworkInterface {
5353

5454
bool bandwidth(wifi_bandwidth_t bandwidth);
5555
bool enableNAPT(bool enable = true);
56+
bool enableDhcpCaptivePortal();
5657

5758
String SSID(void) const;
5859
uint8_t stationCount();

0 commit comments

Comments
 (0)