先上完整的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import { networkInterfaces } from 'os';
function getLocalAddress() { const netInfo = networkInterfaces(); let localAddress = {}; for ( let niName in netInfo ) { netInfo[niName].forEach(( ni ) => { if ( ni.family === 'IPv4' && ni.internal === false ) { localAddress[niName] = ni.address; } }); } return localAddress; }
console.log(getLocalAddress());
|
首先通过 os
模块获取网络信息,如下:
1
| import { networkInterfaces } from 'os';
|
其中,netInfo
的内容大致如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| { "Wi-Fi": [ { "address": "fe80::58fb:e0d3:b71f:3b49", "netmask": "ffff:ffff:ffff:ffff::", "family": "IPv6", "mac": "ac:1e:cb:4b:07:e3", "internal": false, "cidr": "fe80::58fb:e0d3:b71f:3b49/64", "scopeid": 10 }, { "address": "192.168.1.30", "netmask": "255.255.0.0", "family": "IPv4", "mac": "ac:1e:cb:4b:07:e3", "internal": false, "cidr": "192.168.1.30/16" } ], "eth0": [ ... ], "Loopback Pseudo-Interface 1": [ ... ] }
|
根据如上的内容,可以写一个提取内网本机的 IPv4 地址的函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| function getLocalAddress() { const netInfo = networkInterfaces(); let localAddress = {}; for ( let niName in netInfo ) { netInfo[niName].forEach(( ni ) => { if ( ni.family === 'IPv4' && ni.internal === false ) { localAddress[niName] = ni.address; } }); } return localAddress; }
|
如果需要获取本机的 IPv6 地址,把如上函数的第 12 行的 IPv4
改成 IPv6
即可。
参考资料
* 目前本文并未直接复制以下文章的内容