Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine a user's IP address in node

Tags:

node.js

ip

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) {     // need access to IP address here }) 
like image 558
Shamoon Avatar asked Nov 12 '11 21:11

Shamoon


People also ask

How do I find my public IP address in node JS?

publicIp. v4(). then(ip => { console. log("your public ip address", ip); });

What is node in IP address?

An IP Address node is created in the datastore when a host, network device, printer, or SNMP managed device is scanned successfully. The new IP Address node will only be created if one with the same key does not already exist as a child of that node.


1 Answers

In your request object there is a property called socket, 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.socket.remoteAddress 

(if your node version is below 13, use the deprecated now request.connection.remoteAddress)

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']

like image 94
topek Avatar answered Oct 06 '22 20:10

topek