“正在使用的地址”与 Windows 和 Linux 上的 bind() 之间的区别 - errno=98

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4979425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:09:50  来源:igfitidea点击:

difference between "address in use" with bind() in Windows and on Linux - errno=98

windowslinuxtcpberkeley-sockets

提问by stuck

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.

我有一个侦听端口的小型 TCP 服务器。在调试时,我通常会 CTRL-C 服务器以终止进程。

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

在 Windows 上,我可以快速重新启动服务并且可以重新启动套接字。在 Linux 上,我必须等待几分钟,然后 bind() 成功返回

When bind() is failing it returns errno=98, address in use.

当 bind() 失败时,它返回 errno=98, address in use。

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'.

我想更好地了解实现的差异。Windows 肯定对开发人员更友好,但我有点怀疑 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 正在等待,直到所有可能的客户端都检测到旧套接字已损坏,然后才允许创建新套接字。它可以做到这一点的唯一方法是等待他们超时

is there a way to change this behavior during development in Linux? I'm hoping to duplicate the way Windows does this

有没有办法在 Linux 开发过程中改变这种行为?我希望复制 Windows 执行此操作的方式

回答by Matt Joiner

You want to use the SO_REUSEADDRoption on the socket on Linux. The relevant manpage is socket(7). Here's an exampleof its usage. This questionexplains what happens.

您想SO_REUSEADDR在 Linux 上的套接字上使用该选项。相关的联机帮助页是socket(7). 这是它的用法示例这个问题解释了会发生什么。

Here'sa duplicate of this answer.

是此答案的副本。

On Linux, SO_REUSEADDRallows 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 hereand herefor more.

在 Linux 上,SO_REUSEADDR除非存在活动连接,否则允许您绑定到地址。在 Windows 上,这是默认行为。在 Windows 上,SO_REUSEADDR 允许您另外将多个套接字绑定到相同的地址。请参阅此处此处了解更多信息。