I tried to search a lot to find a way to know the client and server ip address and port number. So far I found:
req.ip
. req
and res
objects, I found that sometimes res.connection._peername
contains the client ip address and port number. But this is not the reliable way to find the port number because in some request this property is missing. So, what is the correct way to know about the port ?listener.address().port
[source] . But can it be known from req
or res
objects ? Actually I want to know the port number from within the middleware where I have req
,res
and next
only( basically app.use(function(req,res,next){...}))
).Any IP address of your machine you can find by using the os module - and that's native to Node. js: var os = require('os'); var networkInterfaces = os. networkInterfaces(); console.
In case you are using http://localhost:<port_number> , then you can get the port number using req. headers. host property.
You can get those four values with these properties if you have a direct connection with the client (no proxies in the way):
req.connection.remoteAddress
req.connection.remotePort
req.connection.localAddress
req.connection.localPort
Relevant node.js source code pointer in net.js: https://github.com/nodejs/node/blob/863952ebadd4909a66bb9da7868bf75bbbe1462d/lib/net.js#L608
Note: While you access these as property values, they are technically implemented as getters. You cannot set these properties.
If there is server infrastructure such as load balancers, proxies, etc... in front of your actual server, the above local values may return the local server, not what the actual public IP/port that the client originally connected to. The only way to retrieve the original public IP/port would be if your infrastructure sets the originals as a HTTP headers (which some proxies set IP, don't know if any proxies set port) since they are not present in the current raw TCP connection from the proxy.
For cases where a proxy is involved, you may also want to look at some HTTP headers:
X-Forwarded-For - The IP address of the client before it went through the proxy
X-Forwarded-Port - The port of the client before it went through the proxy
The X-Forwarded headers may also be a comma separated list if it has gone through multiple proxies such as:
X-Forwarded-For: OriginatingClientIPAddress, proxy1-IPAddress, proxy2-IPAddress
There is also a standard header as of RFC 7239 2014:
Forwarded: for=192.0.2.60; proto=http; by=203.0.113.43
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With