Search this blog

Monday, February 6, 2017

How to find local IP in node js on Linux

Working on a development environment, and still in early infancy, I wanted to find the local IP in node js, as a mean to connect to the local database without a configuration file...  

var os = require( 'os' );
var networkInterfaces = os.networkInterfaces( );
Object.keys(networkInterfaces).forEach(function (ifname) {
  if (!networkInterfaces[ifname][0].internal){
  if (ifname.search("eth")!=-1){
  console.log(networkInterfaces[ifname][0].address);
  }
  }
});

A few remarks: 
  • A more proper way would probably be to use a config file (either a full one, or a small one whose data enables access to a db, in which a config table/collection is used for all the system variables). The following stackoverflow discussion describes several ways to use a config file in node js
  • I'm tired and it is late, but this code, as small as it is, has several limitations:
    • It has been tested only on linux (and it is most probable that different interface names are used on windows).
    • It assumes the order of IPv4 and IPv6 within the neworkInterfaces[ifname] array.
    • It assumes the existence of a "eth" network card (It would be fairly easy to expand it so that wireless cards and other types of linux network interfaces are also handled, in a certain order of inspection, most probably with wireless being the less preferred form of networking).
    • There is no error handling for situations such as if no network card was found.