Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get client IP address with WebSocket (websockets/ws) library in Node.js?

I cannot find the client IP parameter on the client object.

like image 511
Grringo Avatar asked Feb 11 '13 23:02

Grringo


People also ask

How do WebSockets connect to clients?

In order to communicate using the WebSocket protocol, you need to create a WebSocket object; this will automatically attempt to open the connection to the server. The URL to which to connect; this should be the URL to which the WebSocket server will respond.

How do I get data from a WebSocket?

The Message event takes place usually when the server sends some data. Messages sent by the server to the client can include plain text messages, binary data, or images. Whenever data is sent, the onmessage function is fired.


3 Answers

After a bit of messing around trying to figure out which one gives the client (web browser's) IP address, the answer is:

ws._socket.remoteAddress

Or if you have access to req via wss.on('connection', (ws, req) => {}):

req.socket.remoteAddress

You can use this, for example, to GeoIP locate where the user is connecting from.

Edit:

If you're running Node behind an Nginx reverse proxy (or any other reverse proxy for that matter), you may need to use:

req.headers['x-forwarded-for'] || req.socket.remoteAddress

A note on security: If your Node server is available directly as well as through the reverse proxy, you might like to check the remoteAddress before trusting x-forwarded-for. The remote address should be your reverse proxy's IP. There's the odd chance someone could call your service directly and spoof x-forwarded-for.

like image 80
Chris Nolet Avatar answered Oct 16 '22 15:10

Chris Nolet


Got this from printing the keys in the socket object:

> ws._socket.address()
  { port: 8081,
    family: 2,
    address: '127.0.0.1' }

> ws._socket.remoteAddress
  '74.125.224.194'

> ws._socket.remotePort
  41435

I don't have any documentation so I'm not sure how well this is supported across versions :/

like image 30
tpott Avatar answered Oct 16 '22 14:10

tpott


In websocket server, since req.connection is deprecated, you use req.socket.

wss.on('connection', (ws, req) => {
    console.log(req.socket.remoteAddress);
});
like image 4
Mukul Kadel Avatar answered Oct 16 '22 15:10

Mukul Kadel