ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
captive_dns.h
Go to the documentation of this file.
1#pragma once
3// DNS server that answers every name with the access point address, so a phone joining the
4// AP runs its captive portal check against the device. Shared by captive_portal and the
5// web_server AP mode; hides the ESP32 (own implementation) vs Arduino (DNSServer library) split.
6#if defined(USE_CAPTIVE_PORTAL) || defined(USE_WEBSERVER_CAPTIVE)
7#include <memory>
8
12#if defined(USE_ESP32)
14#elif defined(USE_ARDUINO)
15#include <DNSServer.h>
16#endif
17
19
20// The server object only exists while running, so an idle owner (AP not up) pays one pointer.
22 public:
24 bool start(const network::IPAddress &ip) {
25 if (this->dns_server_ != nullptr)
26 return true;
27 auto server = make_unique<DNSServer>();
28#if defined(USE_ESP32)
29 const bool started = server->start(ip);
30#elif defined(USE_ARDUINO)
31 server->setErrorReplyCode(DNSReplyCode::NoError);
32 const bool started = server->start(53, ESPHOME_F("*"), ip);
33#endif
34 if (!started)
35 return false;
36 this->dns_server_ = std::move(server);
37 return true;
38 }
39 void stop() {
40 if (this->dns_server_ == nullptr)
41 return;
42 this->dns_server_->stop();
43 this->dns_server_ = nullptr;
44 }
46 void loop() {
47 if (this->dns_server_ == nullptr)
48 return;
49#if defined(USE_ESP32)
50 this->dns_server_->process_next_request();
51#elif defined(USE_ARDUINO)
52 this->dns_server_->processNextRequest();
53#endif
54 }
55 bool is_running() const { return this->dns_server_ != nullptr; }
56
57 protected:
58 // ESP32: web_server_base::DNSServer from dns_server_esp32_idf.h; Arduino: the library class.
59 std::unique_ptr<DNSServer> dns_server_;
60};
61
62} // namespace esphome::web_server_base
63#endif // USE_CAPTIVE_PORTAL || USE_WEBSERVER_CAPTIVE
void loop()
Answer one pending query; call from the owner's loop() while running.
Definition captive_dns.h:46
bool start(const network::IPAddress &ip)
Returns false when the DNS server could not start; nothing is kept, so is_running() stays false.
Definition captive_dns.h:24
std::unique_ptr< DNSServer > dns_server_
Definition captive_dns.h:59