How to get a local IP address in Node.js?
18 April 2020
When building a web application there are times where our program needs to have the value of our local IP address. So, how can you get a local IP address in Node.js?
Well thankfully there is a native operating system library in Node.js called os and we can utilize it to retrieve the local IP address. The documentation for it can be found here.
Using os.networkInterfaces()we can easily retrieve the IP address amongst other useful properties. In your Node.js file you can try the following:
var os = require( 'os' );
var networkInterfaces = os.networkInterfaces();
var arr = networkInterfaces['Local Area Connection 3']
var ip = arr[1].addressAnd there you have it the local IP address is retrieved with relative ease. Some other useful properties on the networkInterfaces() method include:
addressnetmaskfamilymacinternalscopeidcidr
Further information about these properties can be found in the docs
Using Local IP
Additionally, we can also make use of an external package called local-ip. Simply install it like so:
npm install local-ipAnd in your Node.js file you can interact with it like so:
var iface = 'wlan0';
var localip = require('local-ip')(interface);
console.log('My local ip address on ' + iface + ' is ' + localip);I hope this helped!