我有一个简单的Node.js程序在我的机器上运行,我想获得我的程序正在运行的PC的本地IP地址。我如何在Node.js中获得它?
当前回答
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);
这里有一个简洁的小命令行,它实现了这个功能:
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];
我写了一个Node.js模块,通过查看包含默认网关的网络接口来确定您的本地IP地址。
这比从os.networkInterfaces()或DNS查找主机名更可靠。它可以忽略VMware虚拟接口、环回接口和VPN接口,它可以在Windows、Linux、Mac OS和FreeBSD上工作。在底层,它执行route.exe或netstat并解析输出。
var localIpV4Address = require("local-ipv4-address");
localIpV4Address().then(function(ipAddress){
console.log("My IP address is " + ipAddress);
// My IP address is 10.4.4.137
});
一行程序只用于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地址。
公认的答案是异步的。我想要一个同步版本:
var os = require('os');
var ifaces = os.networkInterfaces();
console.log(JSON.stringify(ifaces, null, 4));
for (var iface in ifaces) {
var iface = ifaces[iface];
for (var alias in iface) {
var alias = iface[alias];
console.log(JSON.stringify(alias, null, 4));
if ('IPv4' !== alias.family || alias.internal !== false) {
debug("skip over internal (i.e. 127.0.0.1) and non-IPv4 addresses");
continue;
}
console.log("Found IP address: " + alias.address);
return alias.address;
}
}
return false;
推荐文章
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法