如何获得Node.js中的本地IP地址?

我不是指

127.0.0.1

而是其他计算机用来访问机器的那个

192.168.1.6

http://nodejs.org/api/os.html#os_os_networkinterfaces

var os = require('os'); var interfaces = os.networkInterfaces(); var addresses = []; for (var k in interfaces) { for (var k2 in interfaces[k]) { var address = interfaces[k][k2]; if (address.family === 'IPv4' && !address.internal) { addresses.push(address.address); } } } console.log(addresses); 

https://github.com/indutny/node-ip

 var ip = require("ip"); console.dir ( ip.address() ); 
 $ npm install --save quick-local-ip 

依靠

 var myip = require('quick-local-ip'); //getting ip4 network address of local system myip.getLocalIP4(); //getting ip6 network address of local system myip.getLocalIP6(); 

我的版本,这是一个紧凑的单一文件脚本所需要的,希望对其他人有用:

 var ifs = require('os').networkInterfaces(); var result = Object.keys(ifs) .map(x => [x, ifs[x].filter(x => x.family === 'IPv4')[0]]) .filter(x => x[1]) .map(x => x[1].address); 

或者回答原来的问题:

 var ifs = require('os').networkInterfaces(); var result = Object.keys(ifs) .map(x => ifs[x].filter(x => x.family === 'IPv4' && !x.internal)[0]) .filter(x => x)[0].address; 

https://github.com/dominictarr/my-local-ip

 $ npm install -g my-local-ip $ my-local-ip 

要么

 $ npm install --save my-local-ip $ node > console.log(require('my-local-ip')()) 

这是一个非常小的模块。