2

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?

Lakshaya U.
  • 1,089
  • 1
  • 5
  • 21
  • Did you look at [`req.ip`](http://expressjs.com/en/4x/api.html#req.ip) and [`req.ips`](http://expressjs.com/en/4x/api.html#req.ips). – jfriend00 Mar 05 '21 at 04:31

1 Answers1

3

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

Nilupul Sandeepa
  • 748
  • 6
  • 20
  • Hi, is there some way to just get ipv4 addresses from the same? When the app is requested from something like a mobile network an ipv6 address is returned, as expected. – Lakshaya U. May 21 '21 at 18:01
  • 1
    It is not good practice to convert IPv6 to IPv4. But if you want to convert it to IPv4 https://stackoverflow.com/questions/8107856/how-to-determine-a-users-ip-address-in-node this question have some answers. But there is no guarantee that converted IPv4 will be the correct equivalent of IPv6. – Nilupul Sandeepa May 24 '21 at 18:02