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

后端 未结 2 1307
-上瘾入骨i
-上瘾入骨i 2021-01-30 16:38

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

相关标签:
2条回答
  • 2021-01-30 17:21

    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 :/

    0 讨论(0)
  • 2021-01-30 17:30

    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.connection.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.connection.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.

    0 讨论(0)
提交回复
热议问题