我有一个简单的Node.js程序在我的机器上运行,我想获得我的程序正在运行的PC的本地IP地址。我如何在Node.js中获得它?
当前回答
公认的答案是异步的。我想要一个同步版本:
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;
其他回答
类似于其他答案,但更简洁:
'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);
对于Underscore.js和Lodash,正确的一行代码是:
var ip = require('underscore')
.chain(require('os').networkInterfaces())
.values()
.flatten()
.find({family: 'IPv4', internal: false})
.value()
.address;
这是我的变体,允许以可移植的方式获得IPv4和IPv6地址:
/**
* Collects information about the local IPv4/IPv6 addresses of
* every network interface on the local computer.
* Returns an object with the network interface name as the first-level key and
* "IPv4" or "IPv6" as the second-level key.
* For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
* (as string) of eth0
*/
getLocalIPs = function () {
var addrInfo, ifaceDetails, _len;
var localIPInfo = {};
//Get the network interfaces
var networkInterfaces = require('os').networkInterfaces();
//Iterate over the network interfaces
for (var ifaceName in networkInterfaces) {
ifaceDetails = networkInterfaces[ifaceName];
//Iterate over all interface details
for (var _i = 0, _len = ifaceDetails.length; _i < _len; _i++) {
addrInfo = ifaceDetails[_i];
if (addrInfo.family === 'IPv4') {
//Extract the IPv4 address
if (!localIPInfo[ifaceName]) {
localIPInfo[ifaceName] = {};
}
localIPInfo[ifaceName].IPv4 = addrInfo.address;
} else if (addrInfo.family === 'IPv6') {
//Extract the IPv6 address
if (!localIPInfo[ifaceName]) {
localIPInfo[ifaceName] = {};
}
localIPInfo[ifaceName].IPv6 = addrInfo.address;
}
}
}
return localIPInfo;
};
下面是同一个函数的CoffeeScript版本:
getLocalIPs = () =>
###
Collects information about the local IPv4/IPv6 addresses of
every network interface on the local computer.
Returns an object with the network interface name as the first-level key and
"IPv4" or "IPv6" as the second-level key.
For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
(as string) of eth0
###
networkInterfaces = require('os').networkInterfaces();
localIPInfo = {}
for ifaceName, ifaceDetails of networkInterfaces
for addrInfo in ifaceDetails
if addrInfo.family=='IPv4'
if !localIPInfo[ifaceName]
localIPInfo[ifaceName] = {}
localIPInfo[ifaceName].IPv4 = addrInfo.address
else if addrInfo.family=='IPv6'
if !localIPInfo[ifaceName]
localIPInfo[ifaceName] = {}
localIPInfo[ifaceName].IPv6 = addrInfo.address
return localIPInfo
console.log(getLocalIPs())的示例输出
{ lo: { IPv4: '127.0.0.1', IPv6: '::1' },
wlan0: { IPv4: '192.168.178.21', IPv6: 'fe80::aa1a:2eee:feba:1c39' },
tap0: { IPv4: '10.1.1.7', IPv6: 'fe80::ddf1:a9a1:1242:bc9b' } }
下面是一段Node.js代码,它将解析ifconfig的输出并(异步地)返回找到的第一个IP地址:
(它只在Mac OS X v10.6 (Snow Leopard)上测试;我希望它也能在Linux上运行。)
var getNetworkIP = (function () {
var ignoreRE = /^(127\.0\.0\.1|::1|fe80(:1)?::1(%.*)?)$/i;
var exec = require('child_process').exec;
var cached;
var command;
var filterRE;
switch (process.platform) {
// TODO: implement for OSes without the ifconfig command
case 'darwin':
command = 'ifconfig';
filterRE = /\binet\s+([^\s]+)/g;
// filterRE = /\binet6\s+([^\s]+)/g; // IPv6
break;
default:
command = 'ifconfig';
filterRE = /\binet\b[^:]+:\s*([^\s]+)/g;
// filterRE = /\binet6[^:]+:\s*([^\s]+)/g; // IPv6
break;
}
return function (callback, bypassCache) {
// Get cached value
if (cached && !bypassCache) {
callback(null, cached);
return;
}
// System call
exec(command, function (error, stdout, sterr) {
var ips = [];
// Extract IP addresses
var matches = stdout.match(filterRE);
// JavaScript doesn't have any lookbehind regular expressions, so we need a trick
for (var i = 0; i < matches.length; i++) {
ips.push(matches[i].replace(filterRE, '$1'));
}
// Filter BS
for (var i = 0, l = ips.length; i < l; i++) {
if (!ignoreRE.test(ips[i])) {
//if (!error) {
cached = ips[i];
//}
callback(error, ips[i]);
return;
}
}
// Nothing found
callback(error, null);
});
};
})();
使用的例子:
getNetworkIP(function (error, ip) {
console.log(ip);
if (error) {
console.log('error:', error);
}
}, false);
如果第二个参数为true,函数将每次执行一次系统调用;否则使用缓存的值。
更新版本
返回所有本地网络地址的数组。
在Ubuntu 11.04 (Natty Narwhal)和Windows XP 32上测试
var getNetworkIPs = (function () {
var ignoreRE = /^(127\.0\.0\.1|::1|fe80(:1)?::1(%.*)?)$/i;
var exec = require('child_process').exec;
var cached;
var command;
var filterRE;
switch (process.platform) {
case 'win32':
//case 'win64': // TODO: test
command = 'ipconfig';
filterRE = /\bIPv[46][^:\r\n]+:\s*([^\s]+)/g;
break;
case 'darwin':
command = 'ifconfig';
filterRE = /\binet\s+([^\s]+)/g;
// filterRE = /\binet6\s+([^\s]+)/g; // IPv6
break;
default:
command = 'ifconfig';
filterRE = /\binet\b[^:]+:\s*([^\s]+)/g;
// filterRE = /\binet6[^:]+:\s*([^\s]+)/g; // IPv6
break;
}
return function (callback, bypassCache) {
if (cached && !bypassCache) {
callback(null, cached);
return;
}
// System call
exec(command, function (error, stdout, sterr) {
cached = [];
var ip;
var matches = stdout.match(filterRE) || [];
//if (!error) {
for (var i = 0; i < matches.length; i++) {
ip = matches[i].replace(filterRE, '$1')
if (!ignoreRE.test(ip)) {
cached.push(ip);
}
}
//}
callback(error, cached);
});
};
})();
使用举例:升级版本
getNetworkIPs(function (error, ip) {
console.log(ip);
if (error) {
console.log('error:', error);
}
}, false);
根据注释,以下是当前版本Node.js的工作原理:
var os = require('os');
var _ = require('lodash');
var ip = _.chain(os.networkInterfaces())
.values()
.flatten()
.filter(function(val) {
return (val.family == 'IPv4' && val.internal == false)
})
.pluck('address')
.first()
.value();
上面一个答案的注释缺少对values()的调用。看起来os.networkInterfaces()现在返回一个对象而不是数组。
推荐文章
- 给一个数字加上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添加必要的输入字段