Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get local IP address in Node.js

I have a simple Node.js program running on my machine and I want to get the local IP address of a PC on which my program is running. How do I get it with Node.js?

like image 742
yojimbo87 Avatar asked Sep 06 '10 16:09

yojimbo87


People also ask

How do I find my local IP address node JS?

Any IP address of your machine you can find by using the os module - and that's native to Node. js: var os = require('os'); var networkInterfaces = os. networkInterfaces(); console.

What is the :: 1 address?

::1 is the loopback address in IPv6. Think of it as the IPv6 version of 127.0. 0.1 .


2 Answers

This information can be found in os.networkInterfaces(), — an object, that maps network interface names to its properties (so that one interface can, for example, have several addresses):

'use strict';  const { networkInterfaces } = require('os');  const nets = networkInterfaces(); const results = Object.create(null); // Or just '{}', an empty object  for (const name of Object.keys(nets)) {     for (const net of nets[name]) {         // Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses         if (net.family === 'IPv4' && !net.internal) {             if (!results[name]) {                 results[name] = [];             }             results[name].push(net.address);         }     } } 
// 'results' {   "en0": [     "192.168.1.101"   ],   "eth0": [     "10.0.0.101"   ],   "<network name>": [     "<ip>",     "<ip alias>",     "<ip alias>",     ...   ] } 
// results["en0"][0] "192.168.1.101" 
like image 99
nodyou Avatar answered Sep 27 '22 21:09

nodyou


Running programs to parse the results seems a bit iffy. Here's what I use.

require('dns').lookup(require('os').hostname(), function (err, add, fam) {   console.log('addr: ' + add); }) 

This should return your first network interface local IP address.

like image 24
Xedecimal Avatar answered Sep 27 '22 21:09

Xedecimal