问题描述
我有一个侦听端口的小型TCP服务器.在调试时,我通常会CTRL-C服务器以终止进程.
I have a small TCP server that listens on a port. While debugging it's common for me to CTRL-C the server in order to kill the process.
在Windows上,我可以快速重新启动服务,并且套接字可以重新启动.在Linux上,我必须等待几分钟,然后bind()成功返回
On Windows I'm able to restart the service quickly and the socket can be rebound. On Linux I have to wait a few minutes before bind() returns with success
bind()失败时,它返回errno = 98,正在使用的地址.
When bind() is failing it returns errno=98, address in use.
我想更好地理解实现之间的差异. Windows肯定对开发人员更友好,但是我有点怀疑Linux在做错误的事情".
I'd like to better understand the differences in implementations. Windows sure is more friendly to the developer, but I kind of doubt Linux is doing the 'wrong thing'.
我最好的猜测是Linux等待所有可能的客户端检测到旧套接字已损坏,然后再允许创建新套接字.唯一的办法就是等待他们超时
My best guess is Linux is waiting until all possible clients have detected the old socket is broken before allowing new sockets to be created. The only way it could do this is to wait for them to timeout
有没有一种方法可以在Linux开发过程中更改此行为?我希望复制Windows的方式
is there a way to change this behavior during development in Linux? I'm hoping to duplicate the way Windows does this
推荐答案
您要在Linux上的套接字上使用SO_REUSEADDR
选项.相关的联机帮助页是 socket(7)
.这是其用法的示例. 此问题说明了会发生什么.
You want to use the SO_REUSEADDR
option on the socket on Linux. The relevant manpage is socket(7)
. Here's an example of its usage. This question explains what happens.
此处是该答案的重复副本.
Here's a duplicate of this answer.
在Linux上,除非存在活动连接,否则SO_REUSEADDR
允许您绑定到地址.在Windows上,这是默认行为.在Windows上,SO_REUSEADDR允许您另外将多个套接字绑定到相同的地址.请参见此处和此处以获取更多信息.
On Linux, SO_REUSEADDR
allows you to bind to an address unless an active connection is present. On Windows this is the default behaviour. On Windows, SO_REUSEADDR allows you to additionally bind multiple sockets to the same addresses. See here and here for more.
这篇关于“使用中的地址"与“使用中的地址"之间的区别在Windows和Linux上使用bind()-errno = 98的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!