I want to discover my Mosquitto MQTT Broker using my ESP with LUA on my LAN. My ESP8266 is on the same network.

I'm running

NodeMCU custom build by frightanic.com
branch: master
commit: 4905381c004bdeaf744a60bb940c1906c2e052d4
SSL: false
modules: bme280,dht,file,gpio,http,mdns,mqtt,net,node,rtctime,sjson,sntp,tmr,uart,wifi
build created on 2019-04-28 18:59
powered by Lua 5.1.4 on SDK 2.2.1(6ab97e9)

all works as expected, when I connect to the broker knowing the IP an port:

m:connect("", 1883, 0, function(client)

But how can I discover the IP address of the device running the broker and the port? Mosquitto is set up like here:


The LUA mdns module doesn't provide discovering, am I right?

1 Answers

hardillb On

The documentation for the NodeMCU mDNS module has a note at the top say that it is only a mDNS server not a client but points to an alternative.


This is a mDNS server module. If you are looking for a mDNS client for NodeMCU (i.e. to query mDNS) then udaygin/nodemcu-mdns-client may be an option.

The readme for the alternative includes an example for resolving local MQTT brokers

mc = require('mdnsclient')
local service_to_query = '_mqtt._tcp' --service pattern to search. this is for mqtt brokers
local query_timeout = 2 -- 2 seconds

-- handler to do some thing useful with mdns query results
local query_result_handler  = function(err,query_result)
    if (query_result ~= nil) then
        print("Got Query results")
        local broker_ip,broker_port = mc.extractIpAndPortFromResults(res,1)
        print('Broker '..broker_ip ..":"..broker_port)
        print('no mqtt brokers found in local network. please ensure that they are running and advertising on mdns')

print('Connecting to wifi')
wifi.sta.config('<SSID>', '<PASSWORD>')
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
    print("\n\tSTA - GOT IP".."\n\tStation IP: "..T.IP)
    mc.mdns_query( service_to_query, query_timeout, T.IP, query_result_handler)