2012-09-10 126 views

回答

16

我不知道如何防彈就是這種方法,但在這裏它是從網絡上收集到的答案:

var http = require('http'); 
http.createServer(function (req, res) 
{ 
    var ip = req.ip || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; 
    if (ip == '127.0.0.1') // exit if it's a particular ip 
     res.end(); 
... 

請,有人在節點更精通 - 指正

16

如果您通過網絡地址限制訪問整個服務器,最好將這些規則放在防火牆中。如果出於某種原因想要在應用層處理它(易於配置,動態授權等),那麼最好在連接時立即執行此操作,而不是等待HTTP請求。

Node.js'http.Server emits a connection event您可以使用它來確定遠程地址並在實際HTTP請求之前(或期間)終止連接。此代碼未經測試,但應讓您開始:

var server = http.createServer(function (req, res) { 
    // Your normal request handling goes here 
}); 

server.on('connection', function (sock) { 
    console.log(sock.remoteAddress); 
    // Put your logic for what to do next based on that remote address here 
}); 

server.listen(80); 
+1

非常好的一點。我目前使用的系統是從nodejs登錄IP,並有一個定期運行的shell腳本來分別更新iptables。當你說'把這些規則放到你的防火牆中,然後到達應用層'之前,你絕對正確。 –

相關問題