通过 os.networkInterfaces 获取本地Ip

| vue 项目中使用

  1. 新建 config/getIp.js

     const os = require('os');
     function getNetworkIp() {
         let needHost = ''; // 打开的host
         try {
             // 获得网络接口列表
             let network = os.networkInterfaces();
             console.log("getNetworkIp -> network", network) // 打印结果见最下方
             for (let dev in network) {
                 let iface = network[dev];
                 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;
     }
     module.exports = getNetworkIp
    
  2. config/index 中引用

const Ip = require('./getIp')
module.exports = {
    dev: { 
        host: Ip(), 
        port: 8080,
        // ...
    }

getNetworkIp -> network 打印结果 :

{
  lo0: [
    {
      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'
    },
    {
      address: '::1',
      netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
      family: 'IPv6',
      mac: '00:00:00:00:00:00',
      internal: true,
      cidr: '::1/128',
      scopeid: 0
    },
    {
      address: 'fe80::1',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: '00:00:00:00:00:00',
      internal: true,
      cidr: 'fe80::1/64',
      scopeid: 1
    }
  ],
  en0: [
    {
      address: 'fe80::1472:702c:1467:91e2',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: 'a4:83:e7:0a:e9:e6',
      internal: false,
      cidr: 'fe80::1472:702c:1467:91e2/64',
      scopeid: 6
    },
    {
      address: '192.168.157.7',
      netmask: '255.255.255.0',
      family: 'IPv4',
      mac: 'a4:83:e7:0a:e9:e6',
      internal: false,
      cidr: '192.168.157.7/24'
    }
  ],
  awdl0: [
    {
      address: 'fe80::3c43:ebff:fef4:5117',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: '3e:43:eb:f4:51:17',
      internal: false,
      cidr: 'fe80::3c43:ebff:fef4:5117/64',
      scopeid: 8
    }
  ],
  utun0: [
    {
      address: 'fe80::db86:dbc1:d4b4:935a',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: '00:00:00:00:00:00',
      internal: false,
      cidr: 'fe80::db86:dbc1:d4b4:935a/64',
      scopeid: 12
    }
  ]
}