Skip to content

Instantly share code, notes, and snippets.

@garywu
Created January 30, 2017 05:47
Show Gist options
  • Save garywu/54b19eaf0d881550ab125208e9f62bd1 to your computer and use it in GitHub Desktop.
Save garywu/54b19eaf0d881550ab125208e9f62bd1 to your computer and use it in GitHub Desktop.
//https://hackernoon.com/cracking-nut-nodejs-express-block-get-remote-request-client-ip-address-e4cdfa461add#.2faupv29q
var express = require(‘express’)
var app = express()
// Part1, defining blacklist
var BLACKLIST =['192.0.0.1'];
// Part2, Geting client IP
var getClientIp = function(req) {
var ipAddress = req.connection.remoteAddress;
if (!ipAddress) {
return '';
}
// convert from "::ffff:192.0.0.1" to "192.0.0.1"
if (ipAddress.substr(0, 7) == "::ffff:") {
ipAddress = ipAddress.substr(7)
}
return ipAddress;
};
//Part3, Blocking Client IP, if it is in the blacklist
app.use(function(req, res, next) {
var ipAddress = getClientIp(req);
if(BLACKLIST.indexOf(ipAddress) === -1){
next();
} else {
res.send(ipAddress + ' IP is not in whiteList')
}
});
app.get(‘/’, function (req, res) {
res.send(‘Hello World!’)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment