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?
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.
::1 is the loopback address in IPv6. Think of it as the IPv6 version of 127.0. 0.1 .
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With