Вот мой вариант, который позволяет получать адреса 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' } }