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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With