How to get the local IP address in Node.js?
I have a simple Node.js program running on my machine, and I need to retrieve the local IP address of the PC it’s running on. How can I achieve this using Node.js?
How to get the local IP address in Node.js?
I have a simple Node.js program running on my machine, and I need to retrieve the local IP address of the PC it’s running on. How can I achieve this using Node.js?
You can use the os module in Node.js to get network interfaces. This method returns all the network interfaces and their details.
Here’s how you can retrieve your local IP address:
const os = require('os');
const networkInterfaces = os.networkInterfaces();
const localIp = networkInterfaces['eth0'].find(details => details.family === 'IPv4').address;
console.log(localIp);
This is a simple and direct way to Nodejs get IP addresses from a specific network interface.
Another method is to use dns.lookup() to resolve the local IP address. This method resolves hostnames to IP addresses:
const dns = require('dns');
dns.lookup(require('os').hostname(), (err, address, family) => {
console.log('Local IP address:', address);
});
This method allows you to nodejs get ip address through DNS lookup by resolving the current machine’s hostname.
If you prefer using an external package for simplicity, you can use the get-ip package, which makes it easy to fetch the local IP address.
First, install the package:
npm install get-ip
Then, use it in your code:
const getIp = require('get-ip');
const localIp = getIp();
console.log(localIp);