Node 获取本机 IPv4 地址

os 核心模块的 networkInterfaces() 方法会返回本机网络相关信息:

{
  WLAN: [
    {
      address: '2408:8469:710:10a1:9c9a:c425:e32d:c536',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: 'f8:28:19:e7:af:4f',
      internal: false,
      cidr: '2408:8469:710:10a1:9c9a:c425:e32d:c536/64',
      scopeid: 0
    },
    {
      address: '2408:8469:710:10a1:116a:f05:e786:82cd',
      netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
      family: 'IPv6',
      mac: 'f8:28:19:e7:af:4f',
      internal: false,
      cidr: '2408:8469:710:10a1:116a:f05:e786:82cd/128',
      scopeid: 0
    },
    {
      address: 'fe80::9c9a:c425:e32d:c536',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: 'f8:28:19:e7:af:4f',
      internal: false,
      cidr: 'fe80::9c9a:c425:e32d:c536/64',
      scopeid: 4
    },
    {
      address: '192.168.156.30',
      netmask: '255.255.255.0',
      family: 'IPv4',
      mac: 'f8:28:19:e7:af:4f',
      internal: false,
      cidr: '192.168.156.30/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',
      internal: true,
      cidr: '::1/128',
      scopeid: 0
    },
    {
      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'
    }
  ]
}

从中我们看到了我们需要的 IP 地址(IPv4),直接遍历获取即可:

const os = require('os')

// 获取本机网络信息
const networkInterfaces = os.networkInterfaces()
// 查找 IPv4 地址
for (const item of networkInterfaces.WLAN) {
  if (item.family === 'IPv4') {
    console.log(item.address)
    break
  }
}

Node 版本:v12.18.2

原文地址:https://www.cnblogs.com/haveadate/p/14618832.html