How to get my external IP address with node.js?

后端 未结 14 1519
情深已故
情深已故 2020-12-06 05:00

I\'m using node.js and I need to get my external IP address, provided by my ISP. Is there a way to achieve this without using a service like http://myexternalip.com/raw ?

14条回答
  •  情深已故
    2020-12-06 05:18

    The simplest answer, based on experience is that you can't get your external IP in most cases without using an external service, since you'll typically be behind a NAT or shielded by a firewall. I say in most cases, since there may be situations where you can get it from your router, but it is too case specific to provide a general answer.

    What you want is simply to choose your favourite http client in NodeJS and find a maintained server that simply responds with the IP address in the body. You can also use a package, but you should see if it is still using a maintained remote server.

    While there are plenty of examples already, here is one that first tries IPv6 and then falls back to IPv4. It leverages axios, since that is what I am comfortable with. Also, unless the optional parameter debug is set to true, the result is either a value or undefined.

    const axios = require('axios');
    
    // replace these URLs with whatever is good for you
    const remoteIPv4Url = 'http://ipv4bot.whatismyipaddress.com/';
    const remoteIPv6Url = 'http://ipv6bot.whatismyipaddress.com/';
    
    // Try getting an external IPv4 address.
    async function getExternalIPv4(debug = false) {
      try {
        const response = await axios.get(remoteIPv4Url);
        if (response && response.data) {
          return response.data;
        }
      } catch (error) {
        if (debug) {
          console.log(error);
        }
      }
      return undefined;
    }
    
    // Try getting an external IPv6 address.
    async function getExternalIPv6(debug = false) {
      try {
        const response = await axios.get(remoteIPv6Url);
        if (response && response.data) {
          return response.data;
        }
      } catch (error) {
        if (debug) {
          console.log(error);
        }
      }
      return undefined;
    }
    
    async function getExternalIP(debug = false) {
      let address;
      // Try IPv6 and then IPv4
      address = await getExternalIPv6(debug);
      if (!address) {
        address = await getExternalIPv4(debug);
      }
      return address;
    }
    
    module.exports { getExternalIP, getExternalIPv4, getExternalIPv6 }
    

    Feel free to suggest improvements.

提交回复
热议问题