Use Arduino development ESP32 (10): DNSServer use demonstration and explanation

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Naisu_kun/article/details/88572906

Article Directory

purpose

Speaking in front WebServerall the time to go through ip address access, imagine if the general Internet domain name as input ( www.baidu.com, www.taobao.cometc.) access, then you need to use DNSServerup. In this paper,
Arduino core for the ESP32 in DNSServeruse for a brief introduction.

Use DNSServermust place the device in APmode, the non- APwords to achieve the same functionality mode, please refer to mDNS.
mDNSCan the non- APuse but there are limitations mode, LAN other equipment must also be open mDNSservices between each other to domain names.

Demo

DNSServerUse the following steps:

  • Introducing appropriate library #include <DNSServer.h>;
  • Statement DNSServerobjects;
  • Using the start()method to start DNS server;
  • Using the processNextRequest()method for processing a request from a client;
#include <WiFi.h>
#include <DNSServer.h> //引入相应库
#include <WebServer.h>

IPAddress local_IP(192, 168, 4, 1); //IP地址
IPAddress gateway(192, 168, 4, 1);  //网关地址
IPAddress subnet(255, 255, 255, 0); //子网掩码

const byte DNS_PORT = 53; //DNS服务端口号,一般为53

DNSServer dnsserver; //声明DNSServer对象
WebServer webserver(80);

void handleRoot() //回调函数
{
  webserver.send(200, "text/plain", "通过域名访问的根页面");
}

void handleP1() //回调函数
{
  webserver.send(200, "text/plain", "通过域名访问的p1页面");
}

void setup()
{
  WiFi.mode(WIFI_AP); //设置为AP模式
  WiFi.softAPConfig(local_IP, gateway, subnet);
  WiFi.softAP("DNSServer example");

  webserver.on("/", handleRoot);
  webserver.on("/p1", handleP1);

  dnsserver.start(DNS_PORT, "example.com", local_IP); //启动DNS服务,example.com即为注册的域名
  webserver.begin();
}

void loop()
{
  dnsserver.processNextRequest(); //处理来自客户端的请求
  webserver.handleClient();
}

Here Insert Picture Description

Common method

  • void processNextRequest()
    A processing request from a client;
  • bool start(const uint16_t &port, const String &domainName, const IPAddress &resolvedIP);
    Start DNSServer, respectively, need to fill in a port number, domain name, IP, domain name can fill *indicates that all jump to the domain name will be here;
  • void stop()
    Stop DNSServer;

to sum up

DNSServerIs relatively simple, there is no more can be said of the other, more content can refer to the following:
https://github.com/espressif/arduino-esp32/tree/master/libraries/DNSServer

Guess you like

Origin blog.csdn.net/Naisu_kun/article/details/88572906