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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。