Grizzly : Drop connection for banned IP
I want to show you how you can block IPs in your Grizzly server. I pretty sure that you can find lot of reasons why you would want that.
I'll use a list from http://iblocklist.com/ as input for my demo.
What you have to do to close the connection from client that isn't wanted is pretty simple.
Controller controller = new Controller();
TCPSelectorHandler tcpSelectorHandler = new TCPSelectorHandler(){
public SelectableChannel acceptWithoutRegistration(SelectionKey key) throws IOException {
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel channel = server.accept();
if (isAddressBanned(channel.socket().getInetAddress())) {
if(s_logger.isDebugEnabled()){
s_logger.debug("This IP [" + channel.socket().getInetAddress() +
"] is banned, the connection will be close");
}
closeChannel(channel);
return null;
}
return channel;
}
};
tcpSelectorHandler.setPort(port);
controller.addSelectorHandler(tcpSelectorHandler);
With that, as soon as a connection is made, Grizzly will validate if the IP is valid and close the connection if required.
I won't show the implementation of "isAddressBanned", because it's not really related to Grizzly, but you can find it in the source code.
You can download the complete source code from here.
- Login or register to post comments
- Printer-friendly version
- survivant's blog
- 986 reads





