Skip to content

Instantly share code, notes, and snippets.

@changtimwu
Last active August 29, 2015 13:58
Show Gist options
  • Save changtimwu/9948003 to your computer and use it in GitHub Desktop.
Save changtimwu/9948003 to your computer and use it in GitHub Desktop.
specify interface to send out multicast packets
os =require 'os'
dgram = require 'dgram'
test_send = (ifaddr)->
MDNS_PORT = 5354 # 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.bind MDNS_PORT, ifaddr, ->
s.addMembership( MDNS_ADDRESS)
s.send new Buffer('abcd'), 0, 4, MDNS_PORT, MDNS_ADDRESS, (err,bytes)->
console.log 'send err=', err
console.log 'send bytes=', bytes
else if ver==8
s.bind MDNS_PORT, ifaddr
s.addMembership( MDNS_ADDRESS)
s.send new Buffer('abcd'), 0, 4, MDNS_PORT, MDNS_ADDRESS, (err,bytes)->
console.log 'send err=', err
console.log 'send bytes=', bytes
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
test_send iface.address
break
@changtimwu
Copy link
Author

tested successfully on windows XP and OSX

@changtimwu
Copy link
Author

not work in node v0.10.

dgram.js:382
    throw new errnoException(process._errno, 'addMembership');
          ^
Error: addMembership EBADF
    at new errnoException (dgram.js:440:11)
    at Socket.addMembership (dgram.js:382:11)
    at test_send (/Users/timwu/Dropbox/programming/coffee/multicast/mcast_iface.coffee:15:7)
    at ReadStream.<anonymous> (/Users/timwu/Dropbox/programming/coffee/multicast/mcast_iface.coffee:71:9)

@changtimwu
Copy link
Author

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