|
| 1 | +#include <chrono> |
| 2 | +#include <system_error> |
| 3 | +#include <vector> |
| 4 | + |
| 5 | +#include "dns_server.hpp" |
| 6 | +#include "logger.hpp" |
| 7 | +#include "wifi.hpp" |
| 8 | + |
| 9 | +using namespace std::chrono_literals; |
| 10 | + |
| 11 | +extern "C" void app_main(void) { |
| 12 | + espp::Logger logger({.tag = "DNS Server Example", .level = espp::Logger::Verbosity::INFO}); |
| 13 | + |
| 14 | + logger.info("Starting DNS Server Example"); |
| 15 | + |
| 16 | +#if CONFIG_ESP32_WIFI_NVS_ENABLED |
| 17 | + // Initialize NVS |
| 18 | + esp_err_t ret = nvs_flash_init(); |
| 19 | + if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { |
| 20 | + ESP_ERROR_CHECK(nvs_flash_erase()); |
| 21 | + ret = nvs_flash_init(); |
| 22 | + } |
| 23 | + ESP_ERROR_CHECK(ret); |
| 24 | +#endif |
| 25 | + |
| 26 | + // Initialize WiFi in AP mode |
| 27 | + std::string ap_ssid = "ESP-DNS-Test"; |
| 28 | + std::string ap_password = "testpassword"; |
| 29 | + |
| 30 | + logger.info("Starting WiFi AP: {}", ap_ssid); |
| 31 | + |
| 32 | + espp::WifiAp ap{espp::WifiAp::Config{ |
| 33 | + .ssid = ap_ssid, |
| 34 | + .password = ap_password, |
| 35 | + .channel = 1, |
| 36 | + .max_number_of_stations = 4, |
| 37 | + }}; |
| 38 | + |
| 39 | + logger.info("WiFi AP started successfully"); |
| 40 | + logger.info("Connect to SSID: {} with password: {}", ap_ssid, ap_password); |
| 41 | + |
| 42 | + // Get the AP IP address |
| 43 | + std::string ap_ip = ap.get_ip_address(); |
| 44 | + logger.info("AP IP Address: {}", ap_ip); |
| 45 | + |
| 46 | + // Create and start DNS server |
| 47 | + logger.info("Starting DNS server on {}:53", ap_ip); |
| 48 | + |
| 49 | + espp::DnsServer::Config dns_config{.ip_address = ap_ip, |
| 50 | + .log_level = espp::Logger::Verbosity::INFO}; |
| 51 | + |
| 52 | + espp::DnsServer dns_server(dns_config); |
| 53 | + std::error_code ec; |
| 54 | + if (!dns_server.start(ec)) { |
| 55 | + logger.error("Failed to start DNS server: {}", ec.message()); |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + logger.info("DNS server started successfully"); |
| 60 | + logger.info("All DNS queries will resolve to: {}", ap_ip); |
| 61 | + logger.info(""); |
| 62 | + logger.info("To test:"); |
| 63 | + logger.info("1. Connect your device to WiFi network '{}'", ap_ssid); |
| 64 | + logger.info("2. Try pinging any domain (e.g., ping google.com)"); |
| 65 | + logger.info("3. All domains should resolve to {}", ap_ip); |
| 66 | + |
| 67 | + // Run forever |
| 68 | + while (true) { |
| 69 | + std::this_thread::sleep_for(1s); |
| 70 | + } |
| 71 | +} |
0 commit comments