visit
The best way dealing with the un-welcome people is kicking him out of your party. The best way dealing with un-welcome IPs is to BLACK LIST.Background about today, an APP service running on Node.js server which included a static HTML website and API service. We got few un-welcome IPs list on hand and my boss told me“Peter, black list them.”. I love Node.js and Express, the design of middleware speedups I get the job done and leaving office early to have a Friday night.
Extracting Client ID in Express.js is super easy, Router and req are tools which accelerating to extract all the client information which included Header, Cookies, Post Body, Get URL Parameters etc.
Putting unwelcome IPs in an array, which will be used in middleware to check where the router is going to direct.
var BLACKLIST =['192.0.0.1'];//better to store as an String in process.env.BLACKLIST
Express provide a super friendly req to fetch the client IP within few line of code.
req.connection.remoteAddress return the IP, could be ipv4 or ipv6.
var getClientIp = function(req) {var ipAddress = req.connection.remoteAddress;
// convert from "::ffff:192.0.0.1" to "192.0.0.1"if (ipAddress.substr(0, 7) == "::ffff:") {ipAddress = ipAddress.substr(7)}
Add an USER BLOCKING middleware function(req, res, next) inside app.use( ), this middleware function will be executed for every request to the app. Like a filter which let the right IPs to go through.
if(BLACKLIST.indexOf(ipAddress) !== -1){next();} else {res.send(ipAddress + ' IP is not in whiteList')}});
// Part1, defining blacklistvar BLACKLIST =['192.0.0.1'];
// Part2, Geting client IPvar 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 blacklistapp.use(function(req, res, next) {var ipAddress = getClientIp(req);
if(BLACKLIST.indexOf(ipAddress) === -1){next();} else {res.send(ipAddress + ' IP is not in whiteList')}});
#Thanks to , corrected the mistake BLACKLIST.indexOf(ipAddress) === -1
1) x-forwarded-for: client, proxy1, proxy2, proxy3If you are running behind a proxy like NGiNX or what have you, only then you should check for ‘x-forwarded-for’
**_2) req.connection.remoteAddress_**Default server is listening to IPv6 connections and the IPV6_V6ONLY flag isn’t set with the result that IPv4 connections are processed by the same socket.
**_3) req.connection.socket.remoteAddress_**On https, req.connection.remoteAddress is undefined, but req.connection.socket.remoteAddress does work
[Javascript] override Object.constructor( )[Expressjs] override res.send
Like this story? It is helpful to others? It helps me know if you’d like to see write more about his topic and helps people see the story, when tap the heart below.