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

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


use externalip package

https://github.com/alsotang/externalip

externalip(function (err, ip) {
  console.log(ip); // => 8.8.8.8
});

npm install --save public-ip from here.

Then

publicIp.v4().then(ip => {
  console.log("your public ip address", ip);
});

And if you want the local machine ip you can use this.

var ip = require("ip");
var a = ip.address();
console.log("private ip address", a);

Tags:

Node.Js