开发者

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜