Skip to content

Instantly share code, notes, and snippets.

@jameshartig
Created January 2, 2011 22:20
Show Gist options
  • Save jameshartig/762874 to your computer and use it in GitHub Desktop.
Save jameshartig/762874 to your computer and use it in GitHub Desktop.
Get IP of user in node.js and CloudFlare-compatible
function getIP(req) {
var ip_address = (req.connection.remoteAddress ? req.connection.remoteAddress : req.remoteAddress);
//check for cloudflare
try {
if (req.headers['cf-connecting-ip']) {
var ipParts = ip_address.split(".");
var cloudFlare = false;
switch (parseInt(ipParts[0])) {
case 204:
//(204.93.177.0 - 204.93.177.255)
//(204.93.240.0 - 204.93.240.255)
if (parseInt(ipParts[1]) == 93 && (parseInt(ipParts[2]) == 240 || parseInt(ipParts[2]) == 177)) {
cloudFlare = true;
}
break
case 199:
//(199.27.128.0 - 199.27.135.255)
if (parseInt(ipParts[1]) == 27 && (parseInt(ipParts[2]) < 136 || parseInt(ipParts[2]) > 127)) {
cloudFlare = true;
}
break
case 173:
//(173.245.48.0 - 173.245.63.255)
if (parseInt(ipParts[1]) == 245 && (parseInt(ipParts[2]) < 64 || parseInt(ipParts[2]) > 47)) {
cloudFlare = true;
}
break
}
if (cloudFlare) {
ip_address = req.headers['cf-connecting-ip'];
}
}
} catch (e) {}
return ip_address;
}
@keverw
Copy link

keverw commented May 25, 2012

Nice for the time but outdated now. I wrote a newer one. https://github.com/keverw/node_CloudFlare

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment