I need to have a UDP server that is able to listen to broadcast messages and reply with a message containing my machine's IP address (the broadcast sender expects my IP to be on the body of the message).
If I bind the server to all available interfaces (by providing only the port) I'm perfectly able to receive broadcasts, like so:
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('message', (msg, rinfo) => {
console.log(msg.toString())
// I need to send my IP address here with server.send()
})
server.bind(44818, () => {
console.log(`Server created at ${server.address().address}`)
})
The problem is that server.address().address returns 0.0.0.0, so I'm unable to return a valid/reachable IP address.
I tried creating one UDP server manually for each available interface on my machine:
const dgram = require('dgram');
const os = require('os');
const interfaces = os.networkInterfaces()
for (const interface in interfaces) {
if (interface !== 'lo') {
const server = dgram.createSocket('udp4');
server.on('message', (msg, rinfo) => {
console.log(msg.toString())
})
server.bind(44818, interfaces[interface][0].address, () => {
console.log(`Server created at ${server.address().address} (${interface})`)
})
}
}
Now server.address().address returns the specific IP address that each server is bound to, but for some reason I'm now unable to receive broadcast messages i.e. the 'message' event is never called.
Any suggestions on how I could do this?