The request-ip package seems to be very effective in this regard
npm install request-ip --save
Below is the usage for this
const requestIp = require('request-ip');
app.use(requestIp.mw())
app.use(function(req, res) {
const ip = req.clientIp;
res.end(ip);
});
It looks for specific headers in the request and falls back to some defaults if they do not exist.
The user ip is determined by the following order:
X-Client-IP
X-Forwarded-For (Header may return multiple IP addresses in the format: "client IP, proxy 1 IP, proxy 2 IP", so we take the the first one.)
CF-Connecting-IP (Cloudflare)
Fastly-Client-Ip (Fastly CDN and Firebase hosting header when forwarded to a cloud function)
True-Client-Ip (Akamai and Cloudflare)
X-Real-IP (Nginx proxy/FastCGI)
X-Cluster-Client-IP (Rackspace LB, Riverbed Stingray)
X-Forwarded, Forwarded-For and Forwarded (Variations of #2)
req.connection.remoteAddress
req.socket.remoteAddress
req.connection.socket.remoteAddress
req.info.remoteAddress
If an IP address cannot be found, it will return null.
References:
https://www.npmjs.com/package/request-ip
Express, node JS. How to get the local IP where the app runs
Below are the properties from the Connection where we get the IP address and the port info.
req.connection.localAddress
req.connection.localPort
However this was not giving the public
References:
https://stackoverflow.com/questions/38423930/how-to-retrieve-client-and-server-ip-address-and-port-number-in-node-js
No comments:
Post a Comment