Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServerSocket reuseAddress allow bind to an already bound port?

When using Netty, I was surprised that if I use reuseAddress option, it allows a ServerSocket to bind to the same address without raising an "already bind exception"

        ServerBootstrap bootstrap = new ServerBootstrap(
                new NioServerSocketChannelFactory(Executors
                        .newCachedThreadPool(), Executors.newCachedThreadPool()));
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline p = pipeline();
                p.addLast("handler", new DummyHandler());
                return p;
            }
        });
        bootstrap.setOption("reuseAddress", true);
        bootstrap.bind(new InetSocketAddress(2000));
        bootstrap.bind(new InetSocketAddress(2000));

I just thought that reuseAddress allows a new socket to reuse a close-wait socket, but this is different. The following is the result of a netstat command

  C:\Users\secmask>netstat -a -n|grep 2000
  TCP    0.0.0.0:2000           0.0.0.0:0              LISTENING
  TCP    0.0.0.0:2000           0.0.0.0:0              LISTENING

Am I missing something? What's going on?

like image 928
secmask Avatar asked Feb 18 '11 16:02

secmask


2 Answers

What you are seeing is what reuseAddress is supposed to do. Multiple sockets can be bound to the same IP/Port at the same time, regardless of their states.

like image 157
Remy Lebeau Avatar answered Nov 14 '22 20:11

Remy Lebeau


I assume that Windows allows this due to history. It is a bit of a security issue. See http://msdn.microsoft.com/en-us/library/ms740618 for some information about how the involved options interact. Which socket gets a connection is undefined. Maybe if you narrow down the version of Windows you are using you could narrow down what the response will be although it is probably just to not depend on it.

like image 27
Michael Hunter Avatar answered Nov 14 '22 19:11

Michael Hunter