The Source for Java Technology Collaboration
User: Password:
Register | Login help    

Search

Online Books:
java.net on MarkMail:


Grizzly : Drop connection for banned IP

Posted by survivant on January 22, 2009 at 6:52 PM PST
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.
Related Topics >> Open Source      
Comments
Comments are listed in date ascending order (oldest first)