1

I tried to get IP address of clients system who is using my website through java script and failed.I didn't want to use third parties such as "https://jsonip.com/" to retrieve this information.I know it is possible with Node.js and tried it but failed since this code it is not running.

var express = require('express');
var app = express();
var http = require('http');
app.post('/testurl', function(req, res) {
    console.log(req.connection.remoteAddress);
});

Please help me.

Hari Krishna
  • 2,372
  • 2
  • 11
  • 24

2 Answers2

8

Its a part of the request

req.connection.remoteAddress

you can get it like this

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

app.get('/', function(req, res) {
  res.send('your IP is: ' + req.connection.remoteAddress);
});

app.listen(1337);
R. Gulbrandsen
  • 3,648
  • 1
  • 22
  • 35
  • 1
    I am getting "your IP is: ::1" as responce.but ip must be like example 192.168.23.78 right.can you help me. – Hari Krishna Jan 25 '17 at 08:29
  • yeah.. thats because you're running your app from localhost and testing it from the same machine. Try to access it over LAN or push your code to an external webserver and you'll see the IP changes. tl;dr; ::1 === IPv6 of localhost – R. Gulbrandsen Jan 25 '17 at 08:32
  • 2
    Thank you very much for the help. – Hari Krishna Jan 25 '17 at 08:38
  • apparently the req.connection is now deprecated in node v16.x.x, use req.socket instead – E-WAVE Jan 20 '22 at 13:03
2

::1 is IPv6 of localhost.

If you are only willing to listen to IPv4, use:

app.listen(3000, '127.0.0.1');

Reference: https://stackoverflow.com/a/30463191/2013580

Community
  • 1
  • 1
zurfyx
  • 31,043
  • 20
  • 111
  • 145