I need to get local IP of my computer in react js app. Can anyone please suggest a good way to do it?
Asked
Active
Viewed 8,447 times
5
-
3Why do you need to do that? You've tagged electron, so maybe an approach that works with Electron is what you need, e.g. https://stackoverflow.com/questions/10750303/how-can-i-get-the-local-ip-address-in-node-js – AKX Jan 14 '22 at 14:10
-
1Local LAN IP? Or public internet-facing IP, if any? IPv4? IPv6? What if your device has more than one active network interface, should it return all the assigned IPs? And yeah...why does your application need to know? – ADyson Jan 14 '22 at 14:12
1 Answers
2
Any IP address of your machine you can find by using the os
module - and that's native to Node.js:
const os = require('os');
const networkInterfaces = os.networkInterfaces();
const ip = networkInterfaces['eth0'][0]['address']
console.log(networkInterfaces);
Update: Window OS solution
const { networkInterfaces } = require('os');
const getIPAddress = () => {
const nets = networkInterfaces();
const results = {};
for (const name of Object.keys(nets)) {
for (const net of nets[name]) {
// Retrieve only IPv4 addresses
if (net.family === 'IPv4' && !net.internal) {
if (!results[name]) {
results[name] = [];
}
results[name].push(net.address);
}
}
}
// Return the first IP address for the first NIC found
const nicNames = Object.keys(results);
if (nicNames.length > 0) {
const firstNICAddresses = results[nicNames[0]];
if (firstNICAddresses.length > 0) {
return firstNICAddresses[0];
}
}
// No IP address found
return null;
};
const ipAddress = getIPAddress();
console.log(ipAddress);
This solution retrieves all network interfaces and their associated IP addresses using the os.networkInterfaces() method. It then filters out all IPv4 addresses that are internal (e.g., loopback) and stores them in an object indexed by NIC names.
Finally, the code returns the first IP address found for the first NIC in the object, or null if no IP address was found.

Mile Mijatović
- 2,948
- 2
- 22
- 41
-
1
-
-
@velkoon, I have updated my code with Window OS solution. Upvote if it's usefull for you. :) – Mile Mijatović Mar 06 '23 at 19:38
-
@MahmoudMousaHamad I guess you don't need to install it. It's native to NodeJS, see https://nodejs.org/api/os.html – marpme Mar 06 '23 at 20:12
-
it says: Uncaught TypeError: os.networkInterfaces is not a function and does not work for me – Soudabeh Parsa May 21 '23 at 07:13