fonini
fonini

Reputation: 3351

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

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.

Upvotes: 32

Views: 78146

Answers (16)

Be1newinner
Be1newinner

Reputation: 21

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();

Upvotes: 1

This is just another one-liner:

const axios = require('axios')

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

Upvotes: 0

mgear
mgear

Reputation: 1908

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/

Upvotes: 41

alsotang
alsotang

Reputation: 1605

Use my externalip package on GitHub

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

Upvotes: 9

Andre M
Andre M

Reputation: 7554

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.

Upvotes: 2

Patrick W. McMahon
Patrick W. McMahon

Reputation: 3561

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

Upvotes: 0

eltoro
eltoro

Reputation: 44

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

Upvotes: 1

K.K.
K.K.

Reputation: 31

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.

Upvotes: 0

Jacob Morris
Jacob Morris

Reputation: 554

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

Upvotes: 0

Ekin
Ekin

Reputation: 1955

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

Upvotes: 4

eisbehr
eisbehr

Reputation: 12452

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

Upvotes: 2

Tyguy7
Tyguy7

Reputation: 593

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

Upvotes: 4

Ade Yahya
Ade Yahya

Reputation: 807

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

Upvotes: 2

jtlindsey
jtlindsey

Reputation: 4863

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

Upvotes: 17

Marko Gresak
Marko Gresak

Reputation: 8217

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.

Upvotes: 0

Code Whisperer
Code Whisperer

Reputation: 23662

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

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

Upvotes: -2

Related Questions