os.networkInterfaces()方法是os模块的内置应用程序编程接口,用于获取有关计算机网络接口的信息。
用法:
os.networkInterfaces()
参数:此方法不接受任何参数。
返回值:此方法返回一个对象,其中包含有关每个网络接口的信息。返回的对象将包含网络接口数组,该数组又由以下属性组成:
- address:一个字符串,用于指定分配的网络地址,即IPv4或IPv6 /
- netmask:一个字符串,指定IPv4或IPv6网络掩码。
- family:指定Family的字符串,值为IPv4或IPv6之一。
- mac:一个字符串,指定网络接口的MAC地址。
- internal:布尔值,如果接口为环回一则为true,否则为false。
- scopeid:一个数字,指定IPv6的作用域ID。
- cidr:一个字符串,用于指定分配的IPv4或IPv6地址以及CIDR表示法中的路由前缀。如果网络掩码无效,则将其设置为null。
以下示例说明了Node.js中os.networkInterfaces()方法的使用:
范例1:
// Node.js program to demonstrate the
// os.networkInterfaces() Method
// Allocating os module
const os = require('os');
// Print os.networkInterfaces() value
console.log(os.networkInterfaces());
输出:
{ 'Wi-Fi': [ { address:'fe80::242a:3451:7fb2:3ab1', netmask:'ffff:ffff:ffff:ffff::', family:'IPv6', mac:'b3:52:16:13:de:b9', scopeid:3, internal:false, cidr:'fe80::242a:3451:7fb2:3ab1/64' }, { address:'192.168.0.5', netmask:'255.255.255.0', family:'IPv4', mac:'b3:52:16:13:de:b9', internal:false, cidr:'192.168.0.5/24' } ], 'Loopback Pseudo-Interface 1': [ { address:'::1', netmask:'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', family:'IPv6', mac:'00:00:00:00:00:00', scopeid:0, internal:true, cidr:'::1/128' }, { address:'127.0.0.1', netmask:'255.0.0.0', family:'IPv4', mac:'00:00:00:00:00:00', internal:true, cidr:'127.0.0.1/8' } ] }
范例2:
// Node.js program to demonstrate the
// os.networkInterfaces() Method
// Allocating os module
const os = require('os');
// Print os.networkInterfaces() value
var net_int = os.networkInterfaces();
var no_of_network_interfaces = 0;
for (var key in net_int) {
console.log(key);
var net_infos=net_int[key];
net_infos.forEach(element => {
no_of_network_interfaces++;
console.log("\tinterface:");
for (var attr in element){
console.log("\t\t" + attr +
":" + element[attr] );
}
});
}
console.log("total number of Network "
+ "interfaces is " + no_of_network_interfaces);
输出:
Wi-Fi interface: address:fe80::242a:3451:7fb2:3ab1 netmask:ffff:ffff:ffff:ffff:: family:IPv6 mac:b3:52:16:13:de:b9 scopeid:3 internal:false cidr:fe80::242a:3451:7fb2:3ab1/64 interface: address:192.168.0.5 netmask:255.255.255.0 family:IPv4 mac:b3:52:16:13:de:b9 internal:false cidr:192.168.0.5/24 Loopback Pseudo-Interface 1 interface: address:::1 netmask:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff family:IPv6 mac:00:00:00:00:00:00 scopeid:0 internal:true cidr:::1/128 interface: address:127.0.0.1 netmask:255.0.0.0 family:IPv4 mac:00:00:00:00:00:00 internal:true cidr:127.0.0.1/8 total number of Network interfaces is 4
注意:上面的程序将通过使用 node filename.js
命令。
参考: https://nodejs.org/api/os.html#os_os_networkinterfaces
相关用法
注:本文由纯净天空筛选整理自gekcho大神的英文原创作品 Node.js | os.networkInterfaces() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。