使用Arduino開發ESP32(10):DNSServer使用演示與說明

目的

前面講WebServer的時候都是通過ip地址去訪問的,如果想像一般上網那樣輸入域名(www.baidu.comwww.taobao.com等)訪問的話就需要用到DNSServer了。本文對
Arduino core for the ESP32中DNSServer使用進行簡單介紹。

使用DNSServer必須使設備處於AP模式下,在非AP模式下想實現同樣功能的話請參考mDNS
mDNS可以在非AP模式下使用但也有侷限,局域網中其它設備也必須開啓mDNS服務互相間才能通過域名訪問。

使用演示

DNSServer使用步驟如下:

  • 引入相應庫#include <DNSServer.h>
  • 聲明DNSServer對象;
  • 使用start()方法啓動DNS服務器;
  • 使用processNextRequest()方法處理來自客戶端的請求;
#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();
}

在這裏插入圖片描述

常用方法

  • void processNextRequest()
    處理來自客戶端的請求;
  • bool start(const uint16_t &port, const String &domainName, const IPAddress &resolvedIP);
    啓動DNSServer,分別需要填入端口號、域名、IP,域名可以填寫 * 表示所有域名都會被跳轉至這裏;
  • void stop()
    停止DNSServer;

總結

DNSServer相對比較簡單,這裏也沒其它更多可以說的了,更多內容可以參考如下:
https://github.com/espressif/arduino-esp32/tree/master/libraries/DNSServer

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章