- 需求背景
开发移动端的时候时常需要本地调试,公司的ip地址经常变动,每天调试程序时,总需要cmd、ipconfig(一直重复这样的操作)
为了节省时间,使用了nodejs的os(操作系统来获取IPv4地址)。
首先引入:
const os = require('os');
接着,获取ip地址,ip地址等等信息是放在网络接口列表中的:
let network = os.networkInterfaces();
网络接口列表如下JSON格式:
{
"以太网": [
{
"address": "",
"netmask": "",
"family": "IPv6",
"mac": "",
"scopeid": ,
"internal": false,
"cidr": ""
},
{
"address": "10.1.30.76",
"netmask": "",
"family": "IPv4",
"mac": "",
"internal": false,
"cidr": ""
}
],
"LoopbackPseudo-Interface1": [
{
"address": ":: 1",
"netmask": "",
"family": "IPv6",
"mac": "",
"scopeid": 0,
"internal": true,
"cidr": ""
},
{
"address": "127.0.0.1",
"netmask": "",
"family": "IPv4",
"mac": "",
"internal": true,
"cidr": ""
}
]
}
从网络接口列表可以看到,我们所需要的是以太网的元素中的family为IPv4的那一项的address、而LoopbackPseudo-Interface1里边也有一个family为IPv4,再加上一个唯一的判断条件internal
所以判断条件为:
//alias代表以太网或者其他中的数组中的每一个对象元素
alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal
完整代码:
test.js
var os = require('os')
function getNetworkIp() {
let needHost = '';
try {
// 获得网络接口列表
let network = os.networkInterfaces();
for (let item in network) {
let iface = network[item];
for (let i = 0; i < iface.length; i++) {
let alias = iface[i];
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
needHost = alias.address;
}
}
}
} catch (e) {
needHost = 'localhost';
}
return needHost;
}
console.log(getNetworkIp());
安装了Nodejs的话,在G盘下(可以随意放置)
接着进入G盘(根据你放的位置)
执行:
node.js test.js //test为文件名
如下图: