Search code examples
node.jsudpwiresharkbroadcast

NodeJS How to broadcast a UDP packet


To broadcast UDP to port 65123, I wrote as below.

    let broadcastClient = dgram.createSocket('udp4')
    broadcastClient.on('listening', () => {
      console.log('now listening...')
      broadcastClient.setBroadcast(true)

      const msg = Buffer.from('helele')
      setInterval(() => {
        console.log('send message')
        broadcastClient.send(msg, 65123, '255.255.255.255', (err, bytes) => {
          if (err) console.error('broadcast error', err)
          if (bytes) console.log('bytes', bytes)
        })
      }, 300)
    })
    broadcastClient.bind(65120)

Log said it correctly sent. But I checked with Wireshark, there's was no broadcast message.

enter image description here

What did I wrong?


Solution

  • 255.255.255.255 doesn't mean fully broadcast. So I should get the local broadcasting address like below.

    Broadcast address = (~subnet mask) | (host's IP address)

    Instead 255.255.255.255, by using 192.168.0.255, UDP broadcasting could be succeed.