Skip to content

Instantly share code, notes, and snippets.

@sskaje

sskaje/demo.js

Created May 6, 2020
Embed
What would you like to do?
JavaScript DNS-SD implementation using multicast-dns
//
// Author: sskaje (https://sskaje.me)
//
// https://sskaje.me/2020/05/javascript-dns-sd
//
const dnssd_query_name = '_protocol._tcp.local'
const dnssd_sd_query_name = '_services._dns-sd._udp.local'
const dnssd_service_name = 'My Services'
const dnssd_host_name = 'test.local'
const dnssd_services = {
answers: [
{
name: dnssd_query_name,
type: 'PTR',
ttl : 4500,
data: dnssd_service_name + '.' + dnssd_query_name
}
],
additionals: [
{
name: dnssd_service_name + '.' + dnssd_query_name,
type: 'SRV',
data: {
port : http_port,
weight : 0,
priority: 0,
target : dnssd_host_name
},
ttl: 120,
flush: 1,
},
{
name: dnssd_service_name + '.' + dnssd_query_name,
type: 'TXT',
data: [
"use_https=false",
"http_port="+http_port,
"mqtt_port="+mqtt_port,
"server_ip="+server_ip,
],
ttl: 4500,
flush: 1,
},
{
name: dnssd_host_name,
type: 'A',
ttl : 120,
data: server_ip,
flush: 1,
}
]
};
let mdns = require('multicast-dns')({interface: server_ip});
mdns.on('warning', function (err) {
console.log("Warning: ", err.stack)
})
//mdns.on('response', function (response) {
// console.log('got a response packet:', response)
//})
mdns.on('query', function (query) {
//console.log('got a query packet:', query)
query.questions.forEach(function (q) {
if (q.type === 'PTR' && q.name === dnssd_sd_query_name) {
mdns.respond({
answers: [
{
name: dnssd_sd_query_name,
type: 'PTR',
ttl : 3600,
data: dnssd_query_name
}
]
})
} else if (q.type === 'PTR' && q.name === dnssd_query_name) {
mdns.respond(JSON.parse(JSON.stringify(dnssd_services)))
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.