flyku
Version:
Flyku is an automated, modular development framework. The goal is to reduce duplication of work in the front-end development process, so that you pay more attention to the program itself.
105 lines (91 loc) • 3.12 kB
JavaScript
/**
* 获取本机 IPv4 地址
* @author indutny
* 因为没有npm,不方便引用,所以直接修改 node-ip, github : https://github.com/indutny/node-ip.git
*/
var ip = exports,
os = require('os');
ip.isPrivate = function isPrivate(addr) {
return addr.match(/^10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
addr.match(/^192\.168\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
addr.match(/^172\.16\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
addr.match(/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
addr.match(/^169\.254\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
addr.match(/^fc00:/) != null || addr.match(/^fe80:/) != null;
};
ip.isLoopback = function isLoopback(addr) {
return /^127\.0\.0\.1/.test(addr)
|| /^fe80::1/.test(addr)
|| /^::1/.test(addr);
};
ip.loopback = function loopback(family) {
//
// Default to `ipv4`
//
family = _normalizeFamily(family);
if (family !== 'ipv4' && family !== 'ipv6') {
throw new Error('family must be ipv4 or ipv6');
}
return family === 'ipv4'
? '127.0.0.1'
: 'fe80::1';
};
//
// ### function address (name, family)
// #### @name {string|'public'|'private'} **Optional** Name or security
// of the network interface.
// #### @family {ipv4|ipv6} **Optional** IP family of the address (defaults
// to ipv4).
//
// Returns the address for the network interface on the current system with
// the specified `name`:
// * String: First `family` address of the interface. If not found see `undefined`.
// * 'public': the first public ip address of family.
// * 'private': the first private ip address of family.
// * undefined: First address with `ipv4` or loopback addres `127.0.0.1`.
//
ip.address = function address(name, family) {
var interfaces = os.networkInterfaces(),
all;
//
// Default to `ipv4`
//
family = _normalizeFamily(family);
//
// If a specific network interface has been named,
// return the address.
//
if (name && !~['public', 'private'].indexOf(name)) {
return interfaces[name].filter(function (details) {
details.family = details.family.toLowerCase();
return details.family === family;
})[0].address;
}
all = Object.keys(interfaces).map(function (nic) {
//
// Note: name will only be `public` or `private`
// when this is called.
//
var addresses = interfaces[nic].filter(function (details) {
details.family = details.family.toLowerCase();
if (details.family !== family || ip.isLoopback(details.address)) {
return false;
}
else if (!name) {
return true;
}
return name === 'public'
? !ip.isPrivate(details.address)
: ip.isPrivate(details.address)
});
return addresses.length
? addresses[0].address
: undefined;
}).filter(Boolean);
return !all.length
? ip.loopback(family)
: all[0];
};
function _normalizeFamily(family) {
return family ? family.toLowerCase() : 'ipv4';
}