cli.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env node
  2. var mdns = require('./')()
  3. var path = require('path')
  4. var os = require('os')
  5. var announcing = process.argv.indexOf('--announce') > -1
  6. if (process.argv.length < 3) {
  7. console.error('Usage: %s <hostname>', path.basename(process.argv[1]))
  8. process.exit(1)
  9. }
  10. var hostname = process.argv[2]
  11. if (announcing) {
  12. var ip = getIp()
  13. mdns.on('query', function (query, rinfo) {
  14. query.questions.forEach(function (q) {
  15. if (q.name === hostname) {
  16. console.log('Responding %s -> %s', q.name, ip)
  17. mdns.respond({
  18. answers: [{
  19. type: 'A',
  20. name: q.name,
  21. data: ip
  22. }]
  23. }, {port: rinfo.port})
  24. }
  25. })
  26. })
  27. } else {
  28. mdns.on('response', function (response) {
  29. response.answers.forEach(function (answer) {
  30. if (answer.name === hostname) {
  31. console.log(answer.data)
  32. process.exit()
  33. }
  34. })
  35. })
  36. mdns.query(hostname, 'A')
  37. // Give responses 3 seconds to respond
  38. setTimeout(function () {
  39. console.error('Hostname not found')
  40. process.exit(1)
  41. }, 3000)
  42. }
  43. function getIp () {
  44. var networks = os.networkInterfaces()
  45. var found = '127.0.0.1'
  46. Object.keys(networks).forEach(function (k) {
  47. var n = networks[k]
  48. n.forEach(function (addr) {
  49. if (addr.family === 'IPv4' && !addr.internal) {
  50. found = addr.address
  51. }
  52. })
  53. })
  54. return found
  55. }