0

I have a Node.js app. I am trying to detect connectivity. I know how to check to see if I can reach the internet by pinging Google. However, I'm curious if there's a way to check to see if I'm connected to a network (i.e. a router) before checking to see if I can access the outside world.

Is there a way I can check to see if I'm connected to a network, but not necessarily get to the outside world? If so, how?

I know in JavaScript, I could check the navigator.onLine property. However, the navigator property doesn't exist in Node.

Some User
  • 5,257
  • 13
  • 51
  • 93
  • Here's more convenient answer by me [https://stackoverflow.com/questions/15270902/check-for-internet-connectivity-in-nodejs/55536283#55536283](https://stackoverflow.com/questions/15270902/check-for-internet-connectivity-in-nodejs/55536283#55536283) – Freddy Daniel Apr 05 '19 at 13:19

1 Answers1

2

I would guess your best bet will involve os.networkInterfaces(), as described in the node.js documentation:

The os.networkInterfaces() method returns an object containing only network interfaces that have been assigned a network address.

Each key on the returned object identifies a network interface. The associated value is an array of objects that each describe an assigned network address.

The properties available on the assigned network address object include: ...

  • internal <boolean> - true if the network interface is a loopback or similar interface that is not remotely accessible; otherwise false

So you'll want to look for interfaces where internal is false.

David784
  • 7,031
  • 2
  • 22
  • 29
  • 1
    Quick note: while this answer is technically correct, keep in mind that virtual network adapters (VMWare, VirtualBox, etc.) don't report as `internal: true`, at least not on Windows... this makes it kinda tricky trying to find the local machine's "primary" interface. – Andre Greeff Nov 15 '22 at 11:38