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 ?
you can make this file. const http = require('http'); function WhatsMyIpAddress(callback) { const options = { host: 'ipv4bot.whatismyipaddress.com', port: 80, path: '/' }; http.
How to Get User’s IP Address in Node JS According to Nodejs Documentation, to get the IP address, they suggest following method: var ip = req.connection.remoteAddress; But, there is a catch, if your Node app running on NGINX or any other proxy for that matter, then you will get the local ip address for every request i.e, 127.0.0.1.
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.
How to User’s get IP address in Express JS. First, you need to add the following line, if your server is behind a proxy, Add following line in nginx.conf file: and then req.ip for getting user’s ip address and you can also use above code to get ip address here too.
There is a slight issue, however; the x-forwarded-for header can contain multiple, comma-separated IP addresses. Thankfully, the first IP address in the x-forwarded-for header is typically the correct IP address. With that in mind, consider the following code:
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); }); });
More info https://www.ipify.org/
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With