javascriptnode.jsnetwork-programmingipip-address

Get Local, Active IPv4 Address in Node.js


I'm attempting to develop a program that communicates between devices over the HTTP protocol. If I hardcode the active IP address of the current device (i.e., the local IPv4 address that the network's router has assigned the device), I can accomplish this without issue.

However, I would like the program to determine the local, active IPv4 address automatically, so the code will run properly without modifications on any device, regardless of local IPv4 address.

I've tried using os.networkInterfaces(), but this returns an array containing all of the adapters available to the device. These adapters have differing keys, depending on the OS, device, language, etc., which makes determining the active local IP address difficult.

I've also tried using ip.address() from the NPM "ip" module, but this returns the wrong IP address in some instances. On my desktop (connected via ethernet), it returns the correct local IP (in the 10.x.x.x range). However, on my laptop (connected via WiFi), it returns the IP address of the ethernet adapter (in the 192.168.x.x range)—even when that adapter is not in use.

Both devices should return their IPs in the 10.x.x.x range, in my case, since my router assigns IPs in this range.

When I host servers on both my desktop and laptop at the same time, and then use the NPM "local-devices" module to find local devices, both my desktop and laptop only find IPs in the 10.x.x.x range, which means my laptop can identify and ping my desktop, but my desktop cannot identify and ping my laptop (since the laptop's server is running in the 192.168.x.x range, since this is the IP returned by ip.address()).

So my question boils down to this: how do I determine the current ACTIVE IP address of a device in Node.js? For example, in the case of my laptop, I want to determine the IP address for the WiFi adapter when connected to the network via WiFi (which is in the 10.x.x.x range).


Solution

  • Nevermind, I just realized that you can omit the hostname when using HTTP.createServer().listen(), and Node will host the server on all available local IP addresses, which seems to fix the issue.

    For more context, this was my .listen() previously:

    // ...
    
    server.listen(PORT, HOSTNAME, () => {
      console.log(`Server running at http://${HOSTNAME}:${PORT}/\n`);
    });
    

    ...and this is it now:

    // ...
    
    server.listen(PORT, () => {
      console.log(`Server running on port ${PORT}\n`);
    });