i have a sensor that connects to a router. I need to create something in node.js that can discover the ip of the sensor in the subnetwork and send a message to the sensor.
I am a bit confused.
I have this server written in node.js:
var udp = require('dgram');
// --------------------creating a udp server --------------------
// creating a udp server
var server = udp.createSocket('udp4');
// emits when any error occurs
server.on('error',function(error){
console.log('Error: ' + error);
server.close();
});
// emits on new datagram msg
server.on('message',function(msg,info){
console.log('Mensagem recebida do cliente : ' + msg.toString());
console.log('Recebido %d bytes de %s:%d\n',msg.length, info.address, info.port);
//sending msg
server.send('envio',info.port,'localhost',function(error){
if(error){
client.close();
}else{
console.log('Data sent !!!');
}
});
});
//emits when socket is ready and listening for datagram msgs
server.on('listening',function(){
var address = server.address();
var port = address.port;
var family = address.family;
var ipaddr = address.address;
console.log('Server is listening at port' + port);
console.log('Server ip :' + ipaddr);
console.log('Server is IP4/IP6 : ' + family);
});
//emits after the socket is closed using socket.close();
server.on('close',function(){
console.log('Socket is closed !');
});
server.bind(2222);
// setTimeout(function(){
// server.close();
// },8000);
I have this client:
var udp = require('dgram');
var buffer = require('buffer');
// creating a client socket
var client = udp.createSocket('udp4');
//buffer msg
var data = Buffer.from('T');
client.on('message',function(msg,info){
console.log('Mensagem recebida do server : ' + msg.toString());
console.log('Recebido %d bytes de %s:%d\n',msg.length, info.address, info.port);
});
//sending msg
client.send(data,2222,'localhost',function(error){
if(error){
client.close();
}else{
console.log('Mensagem enviada:' + ' ' + data);
//client.close();
}
});
If i run the server and the client, they change messages.
I have this code that gives me the ip's in the subnetwork:
var fs = require('fs');
fs.readFile('/proc/net/arp', function(err, data) {
if (!!err) return done(err, null);
var output = [];
var devices = data.toString().split('\n');
devices.splice(0,1);
for (i = 0; i < devices.length; i++) {
var cols = devices[i].replace(/ [ ]*/g, ' ').split(' ');
if ((cols.length > 3) && (cols[0].length !== 0) && (cols[3].length !== 0) && cols[3] !== '00:00:00:00:00:00') {
output.push({
ip: cols[0],
mac: cols[3]
});
}
}
console.log(output);
});
In someway i can do what i want with this codes? Anyone have a tutorial or something that can help me?
via Miguel Coelho
No comments:
Post a Comment