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

后端 未结 14 1510
情深已故
情深已故 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:42

    this should work well without any external dependencies (with the exception of ipify.org):

    var https = require('https');
    
    var callback = function(err, ip){
        if(err){
            return console.log(err);
        }
        console.log('Our public IP is', ip);
        // do something here with the IP address
    };
    
    https.get({
        host: 'api.ipify.org',
    }, function(response) {
        var ip = '';
        response.on('data', function(d) {
            ip += d;
        });
        response.on('end', function() {
            if(ip){
                callback(null, ip);
            } else {
                callback('could not get public ip address :(');
            }
        });
    });
    

    You could also use https://httpbin.org

    GET https://httpbin.org/ip

提交回复
热议问题