Search code examples
javascriptreactjselectron

How to get my system local ip using react js


I need to get local IP of my computer in react js app. Can anyone please suggest a good way to do it?


Solution

  • 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.