Created
January 30, 2017 05:47
-
-
Save garywu/54b19eaf0d881550ab125208e9f62bd1 to your computer and use it in GitHub Desktop.
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
//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