Sunday, June 18, 2017

How to get the IP address of a node by its mdns host name in Arduino ESP32

1. Introduction
- The benefit of mDNS is mentioned here.

- This is necessary when our ESP32 want to connect to a gateway/server (node) without knowing its IP address except the mdns host name.
- We will use the function "IPAddress queryHost(char *host)" which is available in the mdns library.
- In order to use this function, our Arduino ESP32 must join in the same network with the node and mdns service is initialized on ESP32.
2. Hardware
No extra hardware
3. Software
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <WiFi.h>
#include <ESPmDNS.h>
#include <WiFiClient.h>

const char* ssid = "dd-wrt";
const char* password = "0000000000";
char * serverHostname = "iotsharing";//only use host name and remove .local

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

    // Connect to WiFi network
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

    if (!MDNS.begin("esp32")) {
        Serial.println("Error setting up MDNS responder!");
        while(1) {
            delay(1000);
        }
    }
    Serial.println("mDNS responder started");
    IPAddress serverIp = MDNS.queryHost(serverHostname);
    Serial.print("IP address of server: ");
    Serial.println(serverIp.toString());
}
void loop(void)
{
}
4. Result
Figure: Host name to IP

5 comments:

Anonymous said...

Great tutorial, thank U :)

Kenny Thum said...

I have some stupid question, what is the different between connected to local IP address, and the server IP address? It is not the same? When ESP32 connected to the network, the router gives the ESP32 device a local IP address...Isn't this local IP address is the server IP??

Regards,
Kenny

iotsharing dotcom said...

Hi Kenny,

Imagining you are standing on the ESP and the IP of ESP will be local. If there are 2 ESPs (A and B) that connect to the same router and A acts as a server and you are standing on B so the IP of A will be IP server.

Kenny Thum said...

@iotsharing,

Thank you for the info! Meanwhile, i do get the IP address of the server is 0.0.0.0, while my local IP address is 192.168.1.103. Is this abnormal??

iotsharing dotcom said...

it is abnormal. your esp did not connect to the network.