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

后端 未结 14 1504
情深已故
情深已故 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.

    0 讨论(0)
  • 2020-12-06 05:19

    Simply use superagent

    var superagent = require('superagent');
    var getip = function () {
      superagent
        .get('http://ip.cn/')
        .set('User-Agent', 'curl/7.37.1')
        .end(function (err, res) {
          if (err) {
            console.log(err);
          }
          var ip = res.text.match(/\d+\.\d+\.\d+\.\d+/)[0];
          console.log(ip)
          // Here is the result
        });
    };
    
    0 讨论(0)
  • 2020-12-06 05:19

    Another little node module is ext-ip. The difference is, that you can use different response options, matching your coding style. It's ready to use out of the box ...

    Promise

    let extIP = require('ext-ip')();
    
    extIP.get().then(ip => {
        console.log(ip);
    })
    .catch(err => {
        console.error(err);
    });
    

    Events

    let extIP = require('ext-ip')();
    
    extIP.on("ip", ip => {
        console.log(ip);
    });
    
    extIP.on("err", err => {
        console.error(err);
    });
    
    extIP();
    

    Callback

    let extIP = require('ext-ip')();
    
    extIP((err, ip) => {
        if( err ){
            throw err;
        }
    
        console.log(ip);
    });
    
    0 讨论(0)
  • 2020-12-06 05:20

    Edit: This was written back in 2013... The site is gone. I'm leaving the example request code for now unless anyone complains but go for the accepted answer.


    http://fugal.net/ip.cgi was similar to that one.

    or you can

    require('http').request({
        hostname: 'fugal.net',
        path: '/ip.cgi',
        agent: false
        }, function(res) {
        if(res.statusCode != 200) {
            throw new Error('non-OK status: ' + res.statusCode);
        }
        res.setEncoding('utf-8');
        var ipAddress = '';
        res.on('data', function(chunk) { ipAddress += chunk; });
        res.on('end', function() {
            // ipAddress contains the external IP address
        });
        }).on('error', function(err) {
        throw err;
    }).end();
    

    Ref: http://www.nodejs.org/api/http.html#http_http_request_options_callback

    0 讨论(0)
  • 2020-12-06 05:23

    node.js has a lot of great built in modules you can use without including any external dependencies. you can make this file.
    WhatsMyIpAddress.js

    const http = require('http');
    
    function WhatsMyIpAddress(callback) {
        const options = {
            host: 'ipv4bot.whatismyipaddress.com',
            port: 80,
            path: '/'
        };
        http.get(options, res => {
            res.setEncoding('utf8');
            res.on("data", chunk => callback(chunk, null));
        }).on('error', err => callback(null, err.message));
    }
    
    module.exports = WhatsMyIpAddress;
    

    Then call it in your main.js like this.

    main.js

    const WhatsMyIpAddress = require('./src/WhatsMyIpAddress');
    WhatsMyIpAddress((data,err) => {
       console.log('results:', data, err);
    });
    
    0 讨论(0)
  • 2020-12-06 05:26

    Can do the same as what they do in Python to get external IP, connect to some website and get your details from the socket connection:

    const net = require('net');
    const client = net.connect({port: 80, host:"google.com"}, () => {
      console.log('MyIP='+client.localAddress);
      console.log('MyPORT='+client.localPort);
    });
    

    *Unfortunately cannot find the original Python Example anymore as reference..


    Update 2019: Using built-in http library and public API from https://whatismyipaddress.com/api

    const http = require('http');
    
    var options = {
      host: 'ipv4bot.whatismyipaddress.com',
      port: 80,
      path: '/'
    };
    
    http.get(options, function(res) {
      console.log("status: " + res.statusCode);
    
      res.on("data", function(chunk) {
        console.log("BODY: " + chunk);
      });
    }).on('error', function(e) {
      console.log("error: " + e.message);
    });
    

    Tested with Node.js v0.10.48 on Amazon AWS server

    0 讨论(0)
提交回复
热议问题