Node.js – How to get my external IP address in node.js app?

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: "https://stackoverflow.com/"
};

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


Update 2021
ipv4bot is closed, here is another public API:

var http = require('http');

http.get({'host': 'api.ipify.org', 'port': 80, 'path': "https://stackoverflow.com/"}, function(resp) {
  resp.on('data', function(ip) {
    console.log("My public IP address is: " + ip);
  });
});


Update 2022
ChatGPT wrote longer example using ipify with json: *Yes, i’ve tested it.
https://gist.github.com/unitycoder/745a58d562180994a3025afcb84c1753

More info https://www.ipify.org/

Leave a Comment