How to recover user IP using Node

Asked

Viewed 1,057 times

1

Hello, how can I make an application that "picks up" the user’s IP using Node?

Currently my code is like this:

const express = require('express');
const handlebars = require('express-handlebars');
var minifyHTML = require('express-minify-html-2');

const app = express();
const PORT = process.env.PORT || 8081;

// MINIFY HTML

app.use(minifyHTML({
    override:      true,
    exception_url: false,
    htmlMinifier: {
        removeComments:            true,
        collapseWhitespace:        true,
        collapseBooleanAttributes: true,
        removeAttributeQuotes:     true,
        removeEmptyAttributes:     true,
        minifyJS:                  true
    }
}));


// HENDLEBARS
app.engine('handlebars', handlebars({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');


// ROTAS
app.get('/', function(req, res) {
    res.render('home');
});

app.use(function(req, res) {
    res.status(404);
    if (req.accepts('html')) {
        res.render('home');
        return;
    }
});

app.listen(PORT);

And the Front-End code is like this:

$.get('https://api.ipify.org?format=json', function(ipv4) {
    var ip = ipv4.ip;
})

I am using Jquery to recover user IP from the front end using this API: https://api.ipify.org?format=json, but would like to do this by back-end, or send the value of the IP variable to Node if possible.

The application is thus: https://my-ip-tk.herokuapp.com/

1 answer

2


Utilizes req.connection.remoteAddress in processing the request.

Example with several possibilities:

const ipCliente = req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
  • I applied the code but it returns me a local IP of the server I believe: https://my-ip-tk.herokuapp.com/

  • This IP is your public internet IP. In my case I returned my IP certificate (Ipv4 in "IP:" and Ipv6 in "IP TEST:") according to the site http://meuip.com.br/ . Each client will appear a different one, what you want is the IP of your right client?

  • One note is that on your development computer the local IP of your network will appear, your client’s IP will only appear even after you publish the application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.