Reliably Get Network IP Address

Your network IP address is the default address that other systems on your network will see as the "server" running Node-RED.

In many environments though, this address is remarkably hard to get hold of reliably. Particularly when you have multiple NIC's. Worse, many of the methods are totally different on different operating systems.

There is one fairly reliable method however, though it does require a connection to the Internet.

To make use of this, you first need to add a global function in settings.js

    functionGlobalContext: {
        // Get your local network IP address
        getNetworkIP: (callback) => {
            // Change the address for a server on your local
            // LAN if you have one (e.g. your router) OR
            // change to something on the Internet like www.google.com

            var socket = net.createConnection(80, '192.168.1.1')
            socket.on('connect', () => {
                callback(socket.address().address)
                socket.end()
            });
            socket.on('error', (e) => {
                callback('No Internet')
            })
        }
    },

Then you need to call that with a function node:

const getNetworkIP = global.get('myGlobals').getNetworkIP

// Take care here. Because this is a callback
// fn, any errors may crash Node-RED. Add extra
// error handling if doing additional processing
getNetworkIP(function (ip) {
    node.send({topic: 'Network IP', payload: ip})
})

NB: I'm assuming you are using Node.JS v6+ here, you will need to adjust for older versions.

[{"id":"767fc1c7.f3d81","type":"inject","z":"6a32c4d1.8c37e4","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"x":260,"y":3160,"wires":[["e350636d.502dc"]]},{"id":"49983085.54981","type":"debug","z":"6a32c4d1.8c37e4","name":"","active":true,"console":"false","complete":"payload","x":690,"y":3160,"wires":[]},{"id":"e350636d.502dc","type":"function","z":"6a32c4d1.8c37e4","name":"myGlobals.networkIP","func":"const getNetworkIP = global.get('myGlobals').getNetworkIP\n\n// Take care here. Because this is a callback\n// fn, any errors may crash Node-RED. Add extra\n// error handling if doing additional processing\ngetNetworkIP(function (ip) {\n    node.send({topic: 'Network IP', payload: ip})\n})\n","outputs":1,"noerr":0,"x":460,"y":3160,"wires":[["49983085.54981"]]}]

Flow Info

Created 7 years, 6 months ago
Updated 5 years ago
Rating: not yet rated

Actions

Rate:

Node Types

Core
  • debug (x1)
  • function (x1)
  • inject (x1)

Tags

  • IP
  • IP-Address
Copy this flow JSON to your clipboard and then import into Node-RED using the Import From > Clipboard (Ctrl-I) menu option