Get IP of computer accessing application via node.js


I have a .Net application where for each access a log is recorded with the IP of the access machine, time etc.

In .Net I use Request.UserHostAddress in the login POST to get the IP of the machine that is accessing the application (the same runs on a local network so this is enough).

Now I'm migrating the application to node and the question arose, is there an equivalent to Request.UserHostAddress in node (process in the backend the information of the machine that is accessing the application) or will it be necessary to obtain the information through the frontend?


You should consider some scenarios to recover IP:

var remoteIp = (req.headers['x-forwarded-for'] || '').split(',').pop() || // Recupera o IP de origem, caso a fonte esteja utilizando proxy
                 req.connection.remoteAddress || // Recupera o endereço remoto da chamada
                 req.socket.remoteAddress || // Recupera o endereço através do socket TCP
                 req.connection.socket.remoteAddress // Recupera o endereço através do socket da conexão

With this you guarantee to retrieve a remote address, whether it is using a proxy or not.

Scroll to Top