我有一个简单的Node.js程序在我的机器上运行,我想获得我的程序正在运行的PC的本地IP地址。我如何在Node.js中获得它?
当前回答
这里有一个简洁的小命令行,它实现了这个功能:
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];
其他回答
安装一个名为ip的模块,如下:
npm install ip
然后使用下面的代码:
var ip = require("ip");
console.log(ip.address());
我只用Node.js就能做到这一点。
node . js:
var os = require( 'os' );
var networkInterfaces = Object.values(os.networkInterfaces())
.reduce((r,a) => {
r = r.concat(a)
return r;
}, [])
.filter(({family, address}) => {
return family.toLowerCase().indexOf('v4') >= 0 &&
address !== '127.0.0.1'
})
.map(({address}) => address);
var ipAddresses = networkInterfaces.join(', ')
console.log(ipAddresses);
作为Bash脚本(需要安装Node.js)
function ifconfig2 ()
{
node -e """
var os = require( 'os' );
var networkInterfaces = Object.values(os.networkInterfaces())
.reduce((r,a)=>{
r = r.concat(a)
return r;
}, [])
.filter(({family, address}) => {
return family.toLowerCase().indexOf('v4') >= 0 &&
address !== '127.0.0.1'
})
.map(({address}) => address);
var ipAddresses = networkInterfaces.join(', ')
console.log(ipAddresses);
"""
}
使用npm ip模块:
var ip = require('ip');
console.log(ip.address());
> '192.168.0.117'
var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress
对上面答案的改进,原因如下:
Code should be as self-explanatory as possible. Enumerating over an array using for...in... should be avoided. for...in... enumeration should be validated to ensure the object's being enumerated over contains the property you're looking for. As JavaScript is loosely typed and the for...in... can be handed any arbitrary object to handle; it's safer to validate the property we're looking for is available. var os = require('os'), interfaces = os.networkInterfaces(), address, addresses = [], i, l, interfaceId, interfaceArray; for (interfaceId in interfaces) { if (interfaces.hasOwnProperty(interfaceId)) { interfaceArray = interfaces[interfaceId]; l = interfaceArray.length; for (i = 0; i < l; i += 1) { address = interfaceArray[i]; if (address.family === 'IPv4' && !address.internal) { addresses.push(address.address); } } } } console.log(addresses);