Find the clients' IP address using an ExpressJS app

Viewed 198

A few days ago, I wrote a nodejs script to log user agents. While my script did work, I could not a find a working way to log the REMOTE_ADDRESS of the client.

app.js:

var express = require('express'), http = require('http'), app = express();

http.createServer(app).listen(8080);

app.get('/', function(req, res) {
    res.send(JSON.stringify(req.get('user-agent')))
    console.log(JSON.stringify(req.get('user-agent')));
});

So, if you curl http://localhost:8080 it returns curl/7.55.1.

However, I could not achieve to log the IP address of the client. Any solutions to it?

1 Answers

request.connection.remoteAddress use this. If your request comes from localhost, IP will be shown as ::1 But if your request comes from different IP, then it will show correct IP. If you want to consider request coming from proxy servers also, take a look at this code: IP Address Code Snippet

Related