I need to get local IP of my computer in react js app. Can anyone please suggest a good way to do it?
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.
npm i --save os
to get it to work. –
Topdrawer I was working on a React.js application and I needed to programmatically retrieve the local system's IP address.
Since React.js runs in the browser, we can't use Node.js modules like os to get the IP address. Instead, we can use the WebRTC API to achieve this.
import { useEffect, useState } from 'react';
function App() {
const [localIp, setLocalIp] = useState('');
console.log('🚀 ~ App ~ localIp:', localIp);
useEffect(() => {
const getLocalIP = async () => {
const ipRegex = /([0-9]{1,3}\.){3}[0-9]{1,3}/;
const pc = new RTCPeerConnection({
iceServers: [],
});
pc.createDataChannel('');
pc.createOffer().then((offer) => pc.setLocalDescription(offer));
pc.onicecandidate = (ice) => {
if (ice && ice.candidate && ice.candidate.candidate) {
const ipMatch = ipRegex.exec(ice.candidate.candidate);
if (ipMatch) {
setLocalIp(ipMatch[0]);
pc.onicecandidate = null;
}
}
};
};
getLocalIP();
}, []);
return (
<div>{localIp}</>
);
}
export default App;
© 2022 - 2024 — McMap. All rights reserved.