Created
January 17, 2012 11:27
-
-
Save qiao/1626318 to your computer and use it in GitHub Desktop.
Node.js get client IP address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// snippet taken from http://catapulty.tumblr.com/post/8303749793/heroku-and-node-js-how-to-get-the-client-ip-address | |
function getClientIp(req) { | |
var ipAddress; | |
// The request may be forwarded from local web server. | |
var forwardedIpsStr = req.header('x-forwarded-for'); | |
if (forwardedIpsStr) { | |
// 'x-forwarded-for' header may return multiple IP addresses in | |
// the format: "client IP, proxy 1 IP, proxy 2 IP" so take the | |
// the first one | |
var forwardedIps = forwardedIpsStr.split(','); | |
ipAddress = forwardedIps[0]; | |
} | |
if (!ipAddress) { | |
// If request was not forwarded | |
ipAddress = req.connection.remoteAddress; | |
} | |
return ipAddress; | |
}; |
function getClientAddress(request){
with(request)
return (headers['x-forwarded-for'] || '').split(',')[0]
|| connection.remoteAddress
}
var getClientAddress = function (req) {
return (req.headers['x-forwarded-for'] || '').split(',')[0]
|| req.connection.remoteAddress;
};
Will that work? If so that is really concise and quite nice. I didn't know you could get so creative with the ||'s!
i am using express 3.4.8 i have enable trusted proxy by app.enable('trust proxy') ,my req.headers does not contain X-Forward-For
The header can be x-forwarded-for
or X-Forwarded-For
, so:
var getClientIp = function(req) {
return (req.headers["X-Forwarded-For"] ||
req.headers["x-forwarded-for"] ||
'').split(',')[0] ||
req.client.remoteAddress;
};
var ip = req.headers["X-Forwarded-For"] || req.connection.remoteAddress;
Always returns the host IP and not the client IP in my case.
X-Forwarded-For? You're checking easily spoofed headers to get an IP?
If you install gentoo you don't need all of this
hi
Can we to find the user's IP telegram?
it is hacked. no use
What should I pass as the "req" parameter?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
半年过去接口似乎变了, 我打印了 req 然后发现下面这样可以用. 总算还好