public
Last active

Node.js get client IP address

  • Download Gist
ip.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// 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;
};

半年过去接口似乎变了, 我打印了 req 然后发现下面这样可以用. 总算还好

getClientIp = (req) ->
  x_ip = req.headers['x-forwarded-for']
  unless x_ip? then x_ip = req.connection.remoteAddress
  x_ip
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!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.