Skip to content

Instantly share code, notes, and snippets.

@BrianLian
Created April 8, 2014 04:52
Show Gist options
  • Save BrianLian/10092284 to your computer and use it in GitHub Desktop.
Save BrianLian/10092284 to your computer and use it in GitHub Desktop.
mcast_iface_receive.coffee
os = require 'os'
dgram = require 'dgram'
test_receive = (ifaddr)->
MDNS_PORT = 5353 # OSX refuses app to use port 5353
MDNS_ADDRESS = "224.0.0.251"
s = dgram.createSocket('udp4')
ver = Number(process.versions.node.split('.')[1])
if ver==10
s.on "error", (err)->
console.log "server error: " + err.stack
s.close()
s.on "message", (msg, rinfo)->
console.log "server got:\n" + msg + "\nfrom " +
rinfo.address + ":" + rinfo.port
s.on "listening", ->
address = s.address()
console.log "server listeming: " +
address.address + ":" + address.port
s.bind MDNS_PORT, '0.0.0.0', ->
s.addMembership MDNS_ADDRESS, ifaddr
s.setMulticastLoopback true
#s.setMulticastTTL 128
#s.addMembership MDNS_ADDRESS
else if ver==8
console.log "unsupported node version:", ver
else
console.log "unsupported node version:", ver
valid_interfaces = ->
vifs=[]
for ifnm, ifaddrs of os.networkInterfaces()
for a in ifaddrs
continue if a.family is 'IPv6' or a.internal is true
vifs.push name:ifnm, address:a.address
vifs
process.stdin.resume()
process.stdin.setEncoding("ascii")
vifs = valid_interfaces()
console.log vifs
console.log 'please select the interface:'
process.stdin.on 'data', (input) ->
input = input.replace('\n', '')
if input not in (iface.name for iface in vifs)
console.log "#{input} is not a valid interface"
return
for iface in vifs
if input == iface.name
count = 2
while count -= 1
test_receive iface.address
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment