If you have a single ESP32 on your network, you can connect to it using its IP address (192.168.1.128, for example). But imagine having several ESP32s scattered around your house. You�ll suddenly find yourself needing to remember multiple IP addresses. Terribly time consuming and no fun. Enter mDNS.

mDNS allows you to access the web server running on your ESP32 using a user-friendly hostname, such as �esp32.local�, rather than fiddling with an IP address. And here�s the best part�even if the IP address of your ESP32 changes, mDNS automatically resolves the new IP address to the same hostname. This means you can keep using the same hostname without worrying about tracking IP address changes.

Pretty amazing, right? In this tutorial, you will learn step-by-step how to set up mDNS on an ESP32. But first, let�s talk about what mDNS is.

What is mDNS?

Thirty years ago, when the Internet was still in its infancy, if you wanted to visit a website, you had to know its IP address. That�s because computers are and were only able to communicate using numbers.

Consider an IP address like 127.33.54.200: it�s lengthy, hard to remember, and certainly not user-friendly. We needed a way to translate these machine-readable IP addresses into something more understandable.

In the early 1980s, Paul Mockapetris introduced a revolutionary system that mapped IP addresses to more memorable domain names�and the Domain Name System (DNS) was born. This system remains the foundation of today�s internet.

When you type a domain name, such as google.com, into your browser, it asks the nameservers if they have the DNS records for that domain. A DNS record is just a file that says �this domain� maps to �this IP address,� and a nameserver is a specialized server that stores such DNS records. For instance, the domain name google.com might be linked to an IP address like 142.250.189.174.

The Domain Name System is one of the foundations of how the internet works; without it, we wouldn�t be able to browse the internet with ease.

But what about a local home network? In such an environment, where devices frequently switch on and off, join and leave the network, and often have dynamic IP addresses, this system becomes impractical, because deploying a dedicated server just to resolve hostnames to IP addresses is not a feasible solution. Is there a simpler way? Yes, indeed�it�s called Multicast DNS, abbreviated as mDNS.

mDNS is a decentralized, peer-to-peer protocol specifically designed for small networks. It enables devices to discover each other�s IP addresses. It works by allowing each device to broadcast its name and IP address to every other device on the network. Obviously, this approach wouldn�t be great for the internet at large, but local networks are small enough that the overhead isn�t a problem.

Key Features and Benefits of mDNS:

  • User-Friendly Hostnames: Devices on the network can be accessed using easily remembered hostnames, such as �esp32.local�, instead of IP addresses.
  • Dynamic IP Handling: Even if a device�s IP address changes, mDNS takes care of resolving the new IP address with the same hostname.
  • Zero Configuration: There�s no need for additional DNS setup, as mDNS operates in a standalone fashion on local networks.
  • Platform Independence: mDNS can be used across various devices and operating systems, making integration seamless.

Let�s go over how to set up mDNS on an ESP32 step by step.

Step 1 � Set Up the Arduino IDE

We will be using the Arduino IDE to program the ESP32, so please ensure you have the ESP32 add-on installed before you proceed:

Step 2 � Connect the ESP32 to your Computer

Use a micro-USB cable to connect your ESP32 board to your computer.

esp32 connected to computer using a usb cable

Step 3 � Define Network Credentials

Before uploading the sketch below, there is one essential modification you need to make. Update the following two variables with your actual WiFi SSID and password.

const char* ssid = "YourNetworkName";  // Enter SSID here
const char* password = "YourPassword";  //Enter Password here

Step 4 � Upload the Code

Here�s a simple sketch that demonstrates setting up mDNS on an ESP32 board. This code connects to a Wi-Fi network, starts an mDNS service, and creates an HTTP server to serve a simple web page. Once uploaded, you should be able to access the web server by navigating to http://esp32.local/ in a web browser.

Go ahead and try out the sketch.

#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>

/*Put your SSID & Password*/
const char* ssid = "YourNetworkName";  // Enter SSID here
const char* password = "YourPassword";  //Enter Password here

WebServer server(80);

void setup() {
  Serial.begin(115200);
  delay(100);

  Serial.println("Connecting to ");
  Serial.println(ssid);

  //connect to your local wi-fi network
  WiFi.begin(ssid, password);

  //check wi-fi is connected to wi-fi network
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected..!");
  
  // Initialize mDNS
  if (!MDNS.begin("esp32")) {   // Set the hostname to "esp32.local"
    Serial.println("Error setting up MDNS responder!");
    while(1) {
      delay(1000);
    }
  }
  Serial.println("mDNS responder started");
  
  server.on("/", handle_OnConnect);
  server.onNotFound(handle_NotFound);

  server.begin();
  Serial.println("HTTP server started");
}
void loop() {
  server.handleClient();
}

void handle_OnConnect() {
  server.send(200, "text/html", "<!DOCTYPE html><html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"></head><body><h1>Hey there!</h1></body></html>"); 
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

Step 5 � Testing the code

After uploading the code, open the Serial Monitor and set the baud rate to 115200. Then, press the EN button on the ESP32. It may take a few moments to connect to your network, after which it will display the messages �mDNS responder started� and �HTTP server started.�

mdns serial monitor output

Next, launch a web browser and navigate to http://esp32.local/. The ESP32 should display a web page with a greeting message.

esp32 mdns web server desktop screenshot

Code Explanation

The sketch begins by including the necessary libraries: WiFi.h for connecting to a WiFi network, WebServer.h for setting up the HTTP server, and ESPmDNS.h for mDNS services.

#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>

Next, two constants, ssid and password, are defined. These are placeholders for your Wi-Fi network�s name (SSID) and password.

const char* ssid = "YourNetworkName";  // Enter SSID here
const char* password = "YourPassword";  //Enter Password here

The next line creates a web server object that listens on port 80 (default HTTP port).

WebServer server(80);

In the setup() function, we first initialize serial communication with the PC.

Serial.begin(115200);

The ESP32 then attempts to join the WiFi network using the WiFi.begin() function, which accepts the SSID (Network Name) and password as arguments.

WiFi.begin(ssid, password);

While the ESP32 attempts to connect to the network, we can check the connectivity status using the WiFi.status() function.

while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.print(".");
}

Next, we simply call the begin() method on an extern variable named MDNS to start the mDNS service. This MDNS variable is an instance of the MDNSResponder class, which provides all of the address resolution functionality.

The call to the previously mentioned begin() method is shown below. As an argument to the method, we pass the desired hostname (which will be used in the URL). It is important to note that the hostname should not be longer than 63 characters.

if (!MDNS.begin("esp32")) {   // Set the hostname to "esp32.local"
  Serial.println("Error setting up MDNS responder!");
  while(1) {
    delay(1000);
  }
}

The following block of code simply sets up a handler for the root URL. When someone accesses the root URL, handle_OnConnect() is called. It also sets up a handler that is called when a requested URL is not found on the server.

server.on("/", handle_OnConnect);
server.onNotFound(handle_NotFound);

Finally, to start the server, we call the begin() method on the server object.

server.begin();

The loop() function continuously checks for incoming client requests and handles them by invoking the handleClient() method on the server object.

void loop() {
  server.handleClient();
}

The handle_OnConnect() is a function that sends an HTML response back to the client when the root URL (�/�) is accessed. It sends a simple HTML page with a greeting message using the server.send() method.

The server.send() method accepts as arguments the HTTP response code, the content type, and the content itself. In our case, we are sending the code 200 (one of the HTTP status codes), which corresponds to the OK response (indicating that the request has been successfully processed). We then specify the content type as �text/html.� Finally, we have a long string that is nothing more than HTML code that creates a simple web page that will display the message �Hey there!�.

void handle_OnConnect() {
  server.send(200, "text/html", "<!DOCTYPE html><html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"></head><body><h1>Hey there!</h1></body></html>"); 
}

If the server receives a request for a URL that does not exist on the server, handle_NotFound() sends a 404 Not Found response.

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

Login
ADS CODE