我有一个简单的Node.js程序在我的机器上运行,我想获得我的程序正在运行的PC的本地IP地址。我如何在Node.js中获得它?
当前回答
对上面答案的改进,原因如下:
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);
其他回答
一行程序只用于macOS的第一个本地主机地址。
当在macOS上开发应用程序时,你想在手机上测试它,并且需要你的应用程序自动选择本地主机IP地址。
require('os').networkInterfaces().en0.find(elm => elm.family=='IPv4').address
这只是提到如何自动查找ip地址。 要测试这个,你可以去终端点击
node
os.networkInterfaces().en0.find(elm => elm.family=='IPv4').address
输出将是您的本地主机IP地址。
如果你喜欢简洁的东西,下面是使用Lodash:
Var OS = require(' OS '); Var _ = require('lodash'); var firstLocalIp = _(os.networkInterfaces()).values().flatten().where({family: 'IPv4', internal: false}).pluck('address').first(); console.log('第一个本地IPv4地址是' + firstLocalIp);
var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress
这些信息可以在os.networkInterfaces()中找到,这是一个对象,它将网络接口名称映射到它的属性(例如,一个接口可以有几个地址):
'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
// 'IPv4' is in Node <= 17, from 18 it's a number 4 or 6
const familyV4Value = typeof net.family === 'string' ? 'IPv4' : 4
if (net.family === familyV4Value && !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"
你可以通过使用os模块找到你机器的任何IP地址-这是Node.js的本机:
var os = require('os');
var networkInterfaces = os.networkInterfaces();
console.log(networkInterfaces);
你所需要做的就是调用os.networkInterfaces(),你会得到一个容易管理的列表——比按联盟运行ifconfig要简单。