Get local IP address in node.js

2019-01-03 04:02发布

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

30条回答
做个烂人
2楼-- · 2019-01-03 04:26

hope this helps

var os = require( 'os' );
var networkInterfaces = os.networkInterfaces( );
var arr = networkInterfaces['Local Area Connection 3']
var ip = arr[1].address;
查看更多
闹够了就滚
3楼-- · 2019-01-03 04:27

Based on a comment above, here's what's working for the current version of Node:

var os = require('os');
var _ = require('lodash');

var ip = _.chain(os.networkInterfaces())
  .values()
  .flatten()
  .filter(function(val) {
    return (val.family == 'IPv4' && val.internal == false)
  })
  .pluck('address')
  .first()
  .value();

The comment on one of the answers above was missing the call to values(). It looks like os.networkInterfaces() now returns an object instead of an array.

查看更多
霸刀☆藐视天下
4楼-- · 2019-01-03 04:27

Similar to other answers but more succinct:

'use strict';

const interfaces = require('os').networkInterfaces();

const addresses = Object.keys(interfaces)
  .reduce((results, name) => results.concat(interfaces[name]), [])
  .filter((iface) => iface.family === 'IPv4' && !iface.internal)
  .map((iface) => iface.address);
查看更多
戒情不戒烟
5楼-- · 2019-01-03 04:29

Here's a neat little one-liner for you which does this functionally:

const ni = require('os').networkInterfaces();
Object
  .keys(ni)
  .map(interf =>
    ni[interf].map(o => !o.internal && o.family === 'IPv4' && o.address))
  .reduce((a, b) => a.concat(b))
  .filter(o => o)
  [0];
查看更多
The star\"
6楼-- · 2019-01-03 04:30

for Linux and MacOS uses, if you want to get your IPs by a synchronous way, try this.

var ips = require('child_process').execSync("ifconfig | grep inet | grep -v inet6 | awk '{gsub(/addr:/,\"\");print $2}'").toString().trim().split("\n");
console.log(ips);

the result will be something like this.

[ '192.168.3.2', '192.168.2.1' ]
查看更多
在下西门庆
7楼-- · 2019-01-03 04:32

One liner for MAC os first localhost address only.

When developing apps on mac os, and want to test it on the phone, and need your app to pick the localhost ip automatically.

require('os').networkInterfaces().en0.find(elm=>elm.family=='IPv4').address

This is just to mention how you can find out the ip address automatically. To test this you can go to terminal hit

node
os.networkInterfaces().en0.find(elm=>elm.family=='IPv4').address

output will be your localhost ip Address.

查看更多
登录 后发表回答