Skip to main content

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 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);
            SocketChannel channel = server.accept();
            if (isAddressBanned(channel.socket().getInetAddress()))  {
                  s_logger.debug("This IP [" + channel.socket().getInetAddress() + 
                  "] is banned, the connection will be close");
                return null;

            return channel;

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 >>