nbroeking
nbroeking

Reputation: 8938

Is there a node way to detect if a network interface comes online?

I have looked at the os module and the ip module but those are really good at telling me the current ip address of the system not if a new one comes online or goes offline. I know I can accomplish this problem using udev rules (I'm on Ubuntu) but I was hoping for a way to do this using only node. How would I go about discovering if a network interface is started?

Upvotes: 1

Views: 1409

Answers (3)

ritshpatidar
ritshpatidar

Reputation: 41

In short, you can use npm package network-interfaces-listener. It will send data every time an(or all) interface becomes online, or offline. Not a perfect solution, but it will do.

I tried the answer of Mike Cluck. The problem I faced with nextTick() approach is that it gets called in the end.

The package creates a separate thread(or worker in nodejs). The worker has setInterval() which calls the passed callback function after every second. The callback compares previous second data, if it does not match, then change has happened, and it calls listener.

Note(edit): The package mentioned is created by me in order to solve the problem.

Upvotes: 0

nbroeking
nbroeking

Reputation: 8938

Unfortunately, there is no event bases way to do this in node. The solution we came up with was to use UDEV to generate events when a device goes offline and comes online.

Upvotes: 0

Mike Cluck
Mike Cluck

Reputation: 32521

You could always setup a listener using process.nextTick and see if the set of interfaces has changed since last time. If so, send out the updates to any listeners.

'use strict';

let os = require('os');

// Track the listeners and provide a way of adding a new one
// You would probably want to put this into some kind of module
// so it can be used in various places
let listeners = [];
function onChange(f) {
    if (listeners.indexOf(f) === -1) {
        listeners.push(f);
    }
}

let oldInterfaces = [];
process.nextTick(function checkInterfaces() {
    let interfaces = os.networkInterfaces();

    // Quick and dirty way of checking for differences
    // Not very efficient
    if (JSON.stringify(interfaces) !== JSON.stringify(oldInterfaces)) {
        listeners.forEach((f) => f(interfaces));
        oldInterfaces = interfaces;
    }

    // Continue to check again on the next tick
    process.nextTick(checkInterfaces);
});

// Print out the current interfaces whenever there's a change
onChange(console.log.bind(console));

Upvotes: 2

Related Questions