SunilWang / node-os-utils

OS Utils - An operating system utility library.
https://www.npmjs.com/package/node-os-utils
MIT License
126 stars 19 forks source link

os.ip() throws error on linux without eth0 #16

Closed jimmyliao11 closed 3 years ago

jimmyliao11 commented 3 years ago
console.log(os.platform(), os.networkInterfaces());

linux {
  lo: [
    {
      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'
    }
  ],
  ens160: [
    {
      address: '192.168.1.100',
      netmask: '255.255.255.0',
      family: 'IPv4',
      mac: '00:aa:bb:cc:dd:ff',
      internal: false,
      cidr: '192.168.1.100/24'
    }
  ]
}
SunilWang commented 3 years ago

What's your question?

jimmyliao11 commented 3 years ago

Thanks for reply. I want to get an IP, but this code will throw an error: TypeError: Cannot read property 'length' of undefined

https://github.com/SunilWang/node-os-utils/blob/master/lib/os.js#L101

    if (platform === 'linux') {
      for (i = 0; i < interfaces.eth0.length; i++) {
        if (os.networkInterfaces().eth0[i].family === 'IPv4') {
          ip = os.networkInterfaces().eth0[i].address
          break
        }
      }

      return ip
    }
SunilWang commented 3 years ago

https://github.com/SunilWang/node-os-utils/pull/19

fix done