Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ESP8266WiFi.h>
- #include <DNSServer.h>
- #include <FS.h> // SPIFFS Library for access to the onboard storage
- #include <ESPAsyncTCP.h> // Async TCP Library is mandatory for Async Web Server
- #include <ESPAsyncWebServer.h> // Async Web Server with built-in WebSocket Plug-in
- #include <ESP8266mDNS.h> // Zero-config Library (Bonjour, Avahi)
- const byte DNS_PORT = 53;
- DNSServer dnsServer;
- AsyncWebServer server(80);
- IPAddress apIP(192, 168, 4, 1);
- void setup() {
- SPIFFS.begin();
- // if DNSServer is started with "*" for domain name, it will reply with
- // provided IP to all DNS request
- dnsServer.start(DNS_PORT, "*", apIP);
- server.serveStatic("/", SPIFFS, "/");
- // replay to all requests with same HTML
- server.onNotFound([](AsyncWebServerRequest *request) {
- if (captivePortal(request)) { // If captive portal redirect instead of displaying the error page.
- return;
- }
- String message = "File Not Found\n\n";
- message += "URI: ";
- message += request->url();
- message += "\nMethod: ";
- message += ( request->method() == HTTP_GET ) ? "GET" : "POST";
- message += "\nArguments: ";
- message += request->args();
- message += "\n";
- for (uint8_t i = 0; i < request->args(); i++ ) {
- message += " " + request->argName ( i ) + ": " + request->arg ( i ) + "\n";
- }
- AsyncWebServerResponse *response = request->beginResponse(404,"text/plain",message);
- response->addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
- response->addHeader("Pragma", "no-cache");
- response->addHeader("Expires", "-1");
- request->send(response);
- });
- server.begin();
- WiFi.mode(WIFI_AP);
- WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
- WiFi.softAP("DNSServer CaptivePortal example");
- if (!MDNS.begin("esp-captive-portal")) {
- Serial.println(F("Error setting up MDNS responder!"));
- }
- // Add Web Server service to mDNS
- MDNS.addService("http", "tcp", 80);
- }
- void loop() {
- dnsServer.processNextRequest();
- }
- boolean captivePortal(AsyncWebServerRequest *request) {
- if (!isIp(request->host()) ) {
- AsyncWebServerResponse *response = request->beginResponse(302,"text/plain","");
- response->addHeader("Location", String("http://" + ipToString(apIP)));
- request->send(response);
- return true;
- }
- return false;
- }
- boolean isIp(String str) {
- for (int i = 0; i < str.length(); i++) {
- int c = str.charAt(i);
- if (c != '.' && (c < '0' || c > '9')) {
- return false;
- }
- }
- return true;
- }
- String ipToString(IPAddress ip) {
- String res = "";
- for (int i = 0; i < 3; i++) {
- res += String((ip >> (8 * i)) & 0xFF) + ".";
- }
- res += String(((ip >> 8 * 3)) & 0xFF);
- return res;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement