-
-
Save igorjs/1903ef8579e704da4a0154bc073ad6d3 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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.