How to determine a user's IP address in node

后端 未结 19 1169
天命终不由人
天命终不由人 2020-11-22 12:46

How can I determine the IP address of a given request from within a controller? For example (in express):

app.post(\'/get/ip/address\', function (req, res) {         


        
19条回答
  •  感动是毒
    2020-11-22 13:04

    In your request object there is a property called connection, which is a net.Socket object. The net.Socket object has a property remoteAddress, therefore you should be able to get the IP with this call:

    request.connection.remoteAddress
    

    See documentation for http and net

    EDIT

    As @juand points out in the comments, the correct method to get the remote IP, if the server is behind a proxy, is request.headers['x-forwarded-for']

提交回复
热议问题