Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Netty allows same port to be bound multiple times by different programs

I'm a noob to Sockets Programming.Maybe am asking a fundamental question. Please bear with me. I wrote a sample netty server and started it from console. It runs fine. The problem i have is that when i run the same server from two console windows, i'd expect one of them to throw 'Address already in use' exception. It does not do that and I dont understand why. Please help.

    public static void main(String[] args) {
    ChannelFactory cf = new NioServerSocketChannelFactory(Executors.newFixedThreadPool(100), new MemoryAwareThreadPoolExecutor(1000,2048,25096,2,TimeUnit.SECONDS));
    //ChannelFactory cf = new OioServerSocketChannelFactory(Executors.newFixedThreadPool(100), Executors.newCachedThreadPool());


    ServerBootstrap bootstrap = new ServerBootstrap(cf);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

        @Override
        public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(new ChannelHandler("test"));
        }
    });

    bootstrap.setOption("child.keepAlive", true);
    bootstrap.setOption("child.tcpNoDelay", true);      
    bootstrap.setOption("child.reuseAddress", true);
    bootstrap.setOption("child.connectTimeoutMillis", 30000);
    //NEVER bootstrap.setOption("child.readWriteFair", true);
    //bootstrap.setOption("disconnect", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("reuseAddress", true);
    bootstrap.setOption("connectTimeoutMillis", 30000);
    bootstrap.setOption("readWriteFair", true);
    bootstrap.bind(new InetSocketAddress(9998));        
}
like image 917
LIFE REFACTORED Avatar asked Aug 24 '12 16:08

LIFE REFACTORED


1 Answers

To sum up the many comments above:

The bootstrap.setOption("reuseAddress", true); option will allow binding to an already bound ip:port combination. This is usually used to be able to restart a server if it crashed/got killed (so while the socket is still in the TIME_WAIT state).

In Windows it is possible to have two completely different programs bind the exact same ip:port. So even if in your app you have bootstrap.setOption("reuseAddress", false); it is still possible for another app (i.e. malicious) that enables SO_REUSEADDR to succesfully bind on your ip:port.

See here for more details: http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621(v=vs.85).aspx

like image 53
Eugen Constantin Dinca Avatar answered Oct 06 '22 08:10

Eugen Constantin Dinca