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