我有一个简单的Node.js程序在我的机器上运行,我想获得我的程序正在运行的PC的本地IP地址。我如何在Node.js中获得它?
当前回答
下面是我获取本地IP地址的实用方法,假设您正在寻找一个IPv4地址,而机器只有一个真实的网络接口。可以很容易地对其进行重构,以返回多接口机器的IP地址数组。
function getIPAddress() {
var interfaces = require('os').networkInterfaces();
for (var devName in interfaces) {
var iface = interfaces[devName];
for (var i = 0; i < iface.length; i++) {
var alias = iface[i];
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)
return alias.address;
}
}
return '0.0.0.0';
}
其他回答
类似于其他答案,但更简洁:
'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);
下面是一个允许你获取本地IP地址的变体(在Mac和Windows上测试):
var
// Local IP address that we're trying to calculate
address
// Provides a few basic operating-system related utility functions (built-in)
,os = require('os')
// Network interfaces
,ifaces = os.networkInterfaces();
// Iterate over interfaces ...
for (var dev in ifaces) {
// ... and find the one that matches the criteria
var iface = ifaces[dev].filter(function(details) {
return details.family === 'IPv4' && details.internal === false;
});
if(iface.length > 0)
address = iface[0].address;
}
// Print the result
console.log(address); // 10.25.10.147
下面是前面例子的一个变种。它会小心过滤掉VMware接口等。如果你不传递索引,它会返回所有地址。否则,您可能希望将其默认值设置为0,然后传递null以获取所有值,但您将整理这些。如果想要添加的话,还可以为regex过滤器传入另一个参数。
function getAddress(idx) {
var addresses = [],
interfaces = os.networkInterfaces(),
name, ifaces, iface;
for (name in interfaces) {
if(interfaces.hasOwnProperty(name)){
ifaces = interfaces[name];
if(!/(loopback|vmware|internal)/gi.test(name)){
for (var i = 0; i < ifaces.length; i++) {
iface = ifaces[i];
if (iface.family === 'IPv4' && !iface.internal && iface.address !== '127.0.0.1') {
addresses.push(iface.address);
}
}
}
}
}
// If an index is passed only return it.
if(idx >= 0)
return addresses[idx];
return addresses;
}
公认的答案是异步的。我想要一个同步版本:
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;
对于Linux和macOS,如果你想通过同步方式获取你的IP地址,试试这个:
var ips = require('child_process').execSync("ifconfig | grep inet | grep -v inet6 | awk '{gsub(/addr:/,\"\");print $2}'").toString().trim().split("\n");
console.log(ips);
结果会是这样的:
['192.168.3.2', '192.168.2.1']
推荐文章
- 给一个数字加上st, nd, rd和th(序数)后缀
- 如何以编程方式触发引导模式?
- setTimeout带引号和不带括号的区别
- 在JS的Chrome CPU配置文件中,'self'和'total'之间的差异
- 用javascript检查输入字符串中是否包含数字
- 如何使用JavaScript分割逗号分隔字符串?
- 在Javascript中~~(“双波浪号”)做什么?
- 谷歌chrome扩展::console.log()从后台页面?
- 未捕获的SyntaxError:
- [].slice的解释。调用javascript?
- jQuery日期/时间选择器
- 我如何预填充一个jQuery Datepicker文本框与今天的日期?
- npm犯错!代码UNABLE_TO_GET_ISSUER_CERT_LOCALLY
- 数组的indexOf函数和findIndex函数的区别
- jQuery添加必要的输入字段