# 获取局域网 IP

使用 os.networkInterfaces() 获取本地网络网络接口的对象

const os = require("os");
const interfaces = os.networkInterfaces();

for (const key in interfaces) {
  const item = interfaces[key];
  for (let i = 0; i < item.length; i++) {
    const ip = item[i];
    if (ip.family === "IPv4" && ip.address !== "127.0.0.1" && !ip.internal) {
      console.log(ip);
    }
  }
}

# os.networkInterfaces()

返回包含已分配网络地址的网络接口的对象。

返回对象上的每个键都标识一个网络接口。 关联的值是每个对象描述一个分配的网络地址的对象数组。

分配的网络地址对象上可用的属性包括:

  • address <string>分配的 IPv4 或 IPv6 地址
  • netmask <string> IPv4 或 IPv6 网络掩码
  • family <string> IPv4 或 IPv6
  • mac <string> 网络接口的 MAC 地址
  • internal <boolean> 如果网络接口是不能远程访问的环回或类似接口,则为 true;否则为 false
  • scopeid <number> 数字的 IPv6 范围 ID(仅在 family 为 IPv6 时指定)
  • cidr <string> 使用 CIDR 表示法的路由前缀分配的 IPv4 或 IPv6 地址。 如果 netmask 无效,则此属性设置为 null。

interfaces 的结构如下

{
  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::5:1e2d:18cb:1b41',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: '14:32:31:ca:2c:f5',
      internal: false,
      cidr: 'fe80::5:1e2d:18cb:1b41/64',
      scopeid: 5
    },
    {
      address: '192.168.31.205',
      netmask: '255.255.255.0',
      family: 'IPv4',
      mac: '14:32:31:ca:2c:f5',
      internal: false,
      cidr: '192.168.31.205/24'
    }
  ],
  awdl0: [
    {
      address: 'fe80::a0dc:9cff:fe99:88d4',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: 'b2:cc:9c:89:88:d2',
      internal: false,
      cidr: 'fe80::a0dc:9cff:fe99:88d4/64',
      scopeid: 10
    }
  ],
  llw0: [
    {
      address: 'fe80::a0dc:9cff:fe99:88d4',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: 'b2:cc:9c:89:88:d2',
      internal: false,
      cidr: 'fe80::a0dc:9cff:fe99:88d4/64',
      scopeid: 11
    }
  ],
  utun0: [
    {
      address: 'fe80::8263:daac:7087:f8bc',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: '00:00:00:00:00:00',
      internal: false,
      cidr: 'fe80::8263:daac:7087:f8bc/64',
      scopeid: 12
    }
  ],
  utun1: [
    {
      address: 'fe80::71f9:8e65:ee0c:3557',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: '00:00:00:00:00:00',
      internal: false,
      cidr: 'fe80::71f9:8e65:ee0c:3557/64',
      scopeid: 13
    }
  ]
}