ServerSocket reuseAddress 允许绑定到已绑定的端口吗?
当使用Netty时,我很惊讶如果我使用reuseAddress选项,它允许ServerSocket绑定到相同的地址在不引发“已绑定异常”的情况下,
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));
我只是认为reuseAddress允许新套接字重用关闭等待套接字,但这是不同的。以下是 netstat 命令的结果
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
我是否遗漏了什么?这是怎么回事?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所看到的是
reuseAddress
应该做的事情。多个套接字可以同时绑定到同一个 IP/端口,无论其状态如何。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.我认为 Windows 允许这样做是因为历史原因。这是一个安全问题。请参阅http://msdn.microsoft.com/en-us/library/ms740618 有关所涉及选项如何交互的一些信息。哪个套接字获取连接是未定义的。也许如果您缩小正在使用的 Windows 版本的范围,您就可以缩小响应的范围,尽管它可能只是不依赖于它。
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.