0

My application is running on ec2 instance. we are using node.js for server side code. We are using socket.io, express to connect the client side code.I have a requirement to capture user's browser ip and send it to server side code. i have tried the below code but it is giving me the server IP details.

 io.sockets.on('connection', function (socket) {
  var socketId = socket.id;
  var clientIp = socket.handshake.headers;
  console.log('connection :', socket.request.connection._peername);
  console.log(socket.request.client._peername.address);

  console.log(clientIp);
});

Is there any ways to capture the user's browser IP, it will be great help. I appreciate your suggestions.

om pal
  • 39
  • 6

2 Answers2

1

In your client side code, you cannot tell what IP address you will be connecting from.

On the server side (express server), you can easily grab the remote IP address from the request, like so:

console.log(req.connection.remoteAddress);

Note that just like any other server, this only tells where you see the connection coming from - the user might be using a VPN, or behind a corporate firewall, etc., in which case the IP address may not have much meaning. Whether this matters to you depends on why you are trying to collect it (logging or something more meaningful).

Don't forget that if your express app is behind a web server (like nginx), you may need to look at the forwarded-for header instead - see related S.O. question How to get remote client address.

Elliot Nelson
  • 10,517
  • 3
  • 25
  • 38
0

we are not yet using nginx. we are just running with nohup command in the background to up the server in ec2. I tried using the below command

console.log(request.socket.remoteAddress)

it gives me the server side ip not the client side ip. We are using this app :8000/index.html in our local system. i want to capture the local system ip. This console.log(req.connection.remoteAddress) gives me TypeError: Cannot read property 'remoteAddress' of undefined

om pal
  • 39
  • 6
  • Could you clarify where you are trying these commands? In the browser console, or in your express application (nodejs)? – Elliot Nelson Jan 11 '19 at 13:18
  • Thanks for your reply.I got the client IP through client side code, from browser it capture the client IP and send to server side code.I was trying in server side code in node js ,so i always get the server IP. – om pal Jan 17 '19 at 18:04