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

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

提交回复
热议问题