Nodejsは本機の住所を取得します.
1961 ワード
Nodejsは、サーバIPを取得するために本マシンのアドレスを取得します.
var os = require('os');
var commonModule = require(global.FRM_CONFIG.REAL_WEB_ROOT + '/Common');
var logger = commonModule.logger(__filename);
/**
* IP
* @param name
* @param family IP IPv4 or IPv5
* @returns ip
*/
exports.getLocalIP = function (name, family) {
//
var ifaces = os.networkInterfaces();
// loopback,
for (var dev in ifaces) {
if (dev.toLowerCase().indexOf('loopback') != -1) {
delete ifaces[dev];
continue;
}
}
var ip = null;
family = family.toUpperCase();
var iface = null;
if (name == null) {
for (var dev in ifaces) {
ifaces[dev].forEach(function (details) {
if (details.family.toUpperCase() === family) {
ip = details.address;
}
});
break;
}
return ip;
}
var nameList = name.split(',');
for (var i = 0, j = nameList.length; i < j; i++) {
var key = nameList[i];
//
if (ifaces[key] == null) {
continue;
}
ifaces[key].forEach(function (details) {
if (details.family.toUpperCase() === family) {
ip = details.address;
}
});
if (ip != null) {
break;
}
}
if (ip == null) {
ip = '127.0.0.1';
logger.error('get ip error, return 127.0.0.1, please check');
}
return ip;
}