Skip to content

Instantly share code, notes, and snippets.

@chrishulbert
Created March 30, 2011 21:46
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save chrishulbert/895382 to your computer and use it in GitHub Desktop.
Save chrishulbert/895382 to your computer and use it in GitHub Desktop.
Service discovery using node.js and ssdp / universal plug n play
var dgram = require('dgram'); // dgram is UDP
// Listen for responses
function listen(port) {
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
});
server.bind(port); // Bind to the random port we were given when sending the message, not 1900
// Give it a while for responses to come in
setTimeout(function(){
console.log("Finished waiting");
server.close();
},2000);
}
function search() {
var message = new Buffer(
"M-SEARCH * HTTP/1.1\r\n" +
"HOST:239.255.255.250:1900\r\n" +
"MAN:\"ssdp:discover\"\r\n" +
"ST:ssdp:all\r\n" + // Essential, used by the client to specify what they want to discover, eg 'ST:ge:fridge'
"MX:1\r\n" + // 1 second to respond (but they all respond immediately?)
"\r\n"
);
var client = dgram.createSocket("udp4");
client.bind(); // So that we get a port so we can listen before sending
listen(client.address().port);
client.send(message, 0, message.length, 1900, "239.255.255.250");
client.close();
}
search();
@harikandakkai
Copy link

Nice post. I had to move the "client.close" statement inside the .send callback to get this run my local PC (Windows 7). I've uploaded a listener code to listen UDP port 1900 here: https://github.com/harikandakkai/ssdp/blob/master/UPnPListener.js

@leonbrag
Copy link

Get this error:

dgram.js:323
throw errnoException(process._errno, 'getsockname')
^
Error: getsockname EINVAL

Any ideas why?

@chr15m
Copy link

chr15m commented Nov 2, 2013

@leonbrag you need to wait for client.bind(); on line 32 to finish - put a callback inside client.bind() and run the other stuff in there.

@gabrielcsapo
Copy link

@chr15m, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment