Explain Codes LogoExplain Codes Logo

Get local IP address in Node.js

javascript
network-interfaces
ipv4-addresses
dns-resolution
Nikita BarsukovbyNikita Barsukov·Aug 26, 2024
TLDR

Cut right to the chase, to fetch your local IP in Node.js, we utilize the cozy os module and its handy networkInterfaces() method. This code snippet below helps you extract the IPv4 address that isn't internal, just as easy as a piece of cake.

const os = require('os'); const localIP = Object.values(os.networkInterfaces()) .flat() .find(iface => iface.family === 'IPv4' && !iface.internal) ?.address; console.log('Local IP Address:', localIP); // Look, Ma! I found my IP address!

Run this exquisite script using Node.js and there you have it, your local IP is printed out right before your eyes in a jiffy.

Detailed run-through the process

The first thing to recognize is that your PC contains multiple network interfaces like Ethernet, Wi-Fi, and sometimes fancy virtual ones. Each player in this team may own one or more assigned IP addresses.

When asked, the networkInterfaces() method returns a bunch of these addresses wrapped in an object with each interface as a property having an array of addresses. It's like asking your Grandma for candies and she hands you the entire candy shop!

Catering for multiple network interfaces

In a case where your system is pumped up with multiple network interfaces (Yeah, it's having a party!), you could refactor the code like this:

const os = require('os'); const getAllIPv4Addresses = () => { const interfaces = os.networkInterfaces(); const allAddresses = []; for (const interface in interfaces) { interfaces[interface].forEach((iface) => { if (iface.family === 'IPv4' && !iface.internal) { allAddresses.push({interface, address: iface.address}); } }); } return allAddresses; }; console.log('All IPv4 Addresses:', getAllIPv4Addresses()); // IPv4 addresses partying in my console!

This code gives back an array of objects mentioning the interface names along with their respective non-internal IPv4 addresses. A bit much but, hey, that's a lot of candies!

Probing beyond the local castle: Getting the public IP

To fetch the majestic public IP address instead of the humble local one, use the node-ip module or the in-built DNS resolution. It's like asking the King's messenger instead of the town crier:

// Using dns module const dns = require('dns'); const os = require('os'); dns.lookup(os.hostname(), (err, address) => { if (err) throw err; console.log('Public IP Address:', address); // Hear ye, Hear ye! Public IP Address, cometh forth! }); // Or using node-ip package const ip = require('ip'); console.log("Public IP Address: ", ip.address()); // Hail the public IP address!

Warning: errors are nasty pests that might creep into network-related operations. So, always, ALWAYS, remember to bash them before they wreak havoc (handle the errors)!

Practical troubleshooting and jokes for nervous breakdowns

While retrieving the local IP address in Node.js, here are some common pot-holes that might halt your carriage:

Watching out for IPv6

The previous examples strictly look for IPv4 addresses. If you haven town criers yelling IPv6 addresses as well, tweak the code to invite both to your tea party.

Ignoring the noisy loopback and internal addresses

During the IP fetching quest, ensure to shun obstructive loopback and internal addresses, since their voices won't reach beyond your PC. Our hero- the code, bravely does this with !iface.internal.

Dealing with Operating System quirks

The land of different operating systems is diverse and colorful. Each might lay out the network interfaces in their own peculiar manners. So, test your scripts under all target operating systems to ensure a smooth journey.