31

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 ?

Thanks.

3
  • 3
    Not if you're behind a NAT Nov 28, 2013 at 18:57
  • I guess this is my case. My laptop IP is 192.168.1.3, my wifi router is 192.168.1.1 and my modem IP provided by the ISP is 201.15.1XX.XXX. I just wanna get the last one.
    – fonini
    Nov 28, 2013 at 19:05
  • not specific to node or any one language. this is a network routing question and cannot be conclusively determined from the host without connecting out.
    – Joe
    Nov 29, 2013 at 2:20

16 Answers 16

39

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

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

var http = require('http');

http.get({'host': 'api.ipify.org', 'port': 80, 'path': '/'}, 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/

6
  • 3
    This does not output the external IP for me
    – pixelfreak
    Dec 13, 2017 at 1:28
  • @pixelfreak which node version? still works for me using v4.4.5
    – mgear
    Dec 16, 2017 at 9:10
  • This outputs my local network/router 192.168.xxx address, not the public address Feb 25, 2019 at 15:20
  • 1
    As of November 10, 2021, ipv4bot has shutdown its public API, see the announcement. I switched to public-ip as suggested by @jtlindsey. Nov 16, 2021 at 16:59
  • 2
    Being picky, resp is a stream, so you must not rely on a single data event thinking that you'll receive the entire data packet sent by the server. For such a small data, if the connection is REALLY congested, you may get half the IP. You must rely on data for concatenating and on end to get the notification that the entire IP has been received. Jun 7, 2022 at 11:47
16

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);
1
  • the ipv4 query fails for me every time. "Query timed out"
    – Tyguy7
    Apr 10, 2017 at 21:01
10

Use my externalip package on GitHub

externalip(function (err, ip) {
  console.log(ip); // => 8.8.8.8
});
3
  • 13
    quite silly to make a package of a few lines to include another package. See also Ade Yahya answer what's inside this package.
    – Codebeat
    Sep 3, 2018 at 19:43
  • 8
    Not really cool to suggest that everyone uses your package that sends user IP info to The People's Republic of China. Jun 2, 2021 at 19:25
  • Popular alternative: github.com/sindresorhus/public-ip Jul 24 at 23:14
4

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

2
  • 2
    Good start, but you are missing one essential thing: Calling end. Anyone trying out this script, don't forget to change the last line like so: }).end();
    – Domi
    Jun 4, 2014 at 11:26
  • The site is offline
    – fonini
    Feb 8, 2018 at 10:09
3

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

2

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
    });
};
2

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);
});
2

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.

1

You may use the request-ip package:

const requestIp = require('request-ip');

// inside middleware handler
const ipMiddleware = function(req, res, next) {
    const clientIp = requestIp.getClientIp(req); 
    next();
};
1
  • This is 'how to get the ip from a request' and not what was initially asked.
    – jaecktec
    Sep 27, 2022 at 7:44
1

Tested and Working;

async function myIP() {
  const response = await fetch("https://api.ipify.org/");
  return await response.text();
}

and call this inside async await like

const ip = await myIP();
0

My shameless plug: canihazip (Disclosure: I'm the author of module, but not of the main page.)

It can be required as a module, exposing a single function that can optionally be passed a callback function an it will return a promise.

It can be also be installed globally and used as CLI.

0

You could very easily use an api solution for retrieving the external IP! I made a ip tracker site made for this kinda thing a few days ago! Here is a snippit of code you could use to get IP!

async function getIp(cb) {
    let output = null;
    let promise = new Promise(resolve => {
        let http = new XMLHttpRequest();
        http.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                output = this.responseText;
                resolve("done");
            }
        }
        http.open("GET", "https://iptrackerz.herokuapp.com/ip", true);
        http.send();
   });
  await promise;
  if (cb != undefined) {
      cb(JSON.parse(output)["ip"]);
  } else {
      return JSON.parse(output)["ip"];
  }
}

Ok, now you have the function getIp()! The way I coded it allows you to do 2 different ways of invoking it! Here they are.

  1. Asynchronous

    async function printIP() { let ip = await getIp(); document.write("Your IP is " + ip); }; printIP();

  2. Callback

    getIp(ip => { document.write("Your IP is " + ip); });

0

I was looking for a solution not relying to other's libraries/ resources, and found this as acceptable alternative:

Just a GET request to external server ( under my control ), where I read req.headers['x-forwarded-for'] and serve it back to my client.

0

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

This is just another one-liner:

const axios = require('axios')

axios.get('https://curlmyip.org/').then(resp => console.log(resp.data))
1
-1

You can use nurl library command ippublic to get this. (disclosure: I made nurl)

> npm install nurl-cli -g
> ippublic;
// 50.240.33.6

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.