Fixing ESP8266mDNS MDNS.queryService() Crashes

1 minute read

I ran into some very frustrating, mysterious errors wile trying to use MDNS.queryService()  in the ESP8266 Arduino SDK. What should have been a simple call to attempt to resolve an mDNS name turned into an exception and stack dump.

Code that looked like this:

Serial.println("About to call MDNS.queryService()");

  int n = MDNS.queryService(HOMEBUS_DEFAULT_NAME, "tcp");
  Serial.printf(" got %d mDNS results\n", n);

  for(int i = 0; i < n; i++) {
    if(MDNS.hostname(i) == HOMEBUS_DEFAULT_NAME) {
      ip[0] = MDNS.IP(i)[0];
      ip[1] = MDNS.IP(i)[1];
      ip[2] = MDNS.IP(i)[2];
      ip[3] = MDNS.IP(i)[3];
    }
  }

led to this:

About to call MDNS.queryService()

Exception (28):
epc1=0x40209972 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

ctx: cont
sp: 3fff0ea0 end: 3fff1130 offset: 01a0

>>>stack>>>
3fff1040:  4020996b 3ffeff48 00000001 401068a0
3fff1050:  6d6f485f 73754265 3fff1000 402098c6
3fff1060:  3fff0044 00000001 3ffe909e 7101000a
3fff1070:  00ffffff 0101000a 61636f6c 745f006c
3fff1080:  3f007063 00000012 00000005 00000004
3fff1090:  00000008 005f0000 3fff0044 4020e9fd
3fff10a0:  3fff1050 00000001 3fff0044 4020ebb0
3fff10b0:  40201506 00001388 3fff0044 3fff0104
3fff10c0:  3ffe8adf 00001388 3fff0044 4020ad67
3fff10d0:  3ffe8adf 3ffeff30 3fff0044 40207bbf
3fff10e0:  40106de0 7101000a 00000000 feefeffe
3fff10f0:  feefeffe feefeffe feefeffe feefeffe
3fff1100:  feefeffe feefeffe feefeffe 3fff0104
3fff1110:  3fffdad0 00000000 3fff00fc 4020fd2c
3fff1120:  feefeffe feefeffe 3fff0110 40100700
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,6)


 ets Jan  8 2013,rst cause:4, boot mode:(1,6)

wdt reset

Turned out there’s a simple solution to this problem.

I’d forgotten to call

1
MDNS.begin()
  first. This prepares the MDNS class for further calls, and the class isn’t written to detect the fact that
1
begin()
  wasn’t called already. Once I made sure to call 
1
MDNS.begin()
before calling 
1
MDNS.queryService()
 the problem went away and the code worked properly.

Updated: