为什么我不是从bind()而是从listen()得到EADDRINUSE?
在 C++ Linux 应用程序中,我调用 socket()、bind() 和 Listen() 来创建服务器套接字。通常,如果应用程序启动两次(使用相同的服务器端口),在第二个进程中,bind() 将失败并出现 EADDRINUSE 错误。但是,现在我遇到这样一种情况:bind() 显然已成功,但后续的listen() 调用引发了 EADDRINUSE 错误...
这可能是一种罕见的竞争条件,但我仍然对它可能发生的情况感兴趣第二个bind()成功,但第二个listen()没有成功。有谁对这样的案例了解更多吗?
这是在 32 位 RHEL 5.3 上。
In a C++ Linux application I'm calling socket(), bind() and listen(), to create a server socket. Usually if the application is started twice (with same server port), in the second process bind() will fail with EADDRINUSE error. However, now I have a case where bind() has apparently succeeded but the subsequent listen() call has thrown the EADDRINUSE error...
This is probably a rare race condition, but I'd be still interested in what cases it could happen that the second bind() succeeds but the second listen() does not. Does anyone know more about such a case?
This is on 32-bit RHEL 5.3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定 Linux 上的情况,但在 Windows 上,如果在调用
bind()
时指定了通配符 IP(INADDR_ANY
等),则底层绑定可能会延迟到调用listen()
或connect()
,因为操作系统当时有更好的机会决定最好使用哪个网络接口。在这种情况下,bind()
不会报告错误。Not sure about Linux, but on Windows, if a wildcard IP (
INADDR_ANY
, etc) is specified when callingbind()
, the underlying binding may be delayed untillisten()
orconnect()
is called, as the OS has a better chance of deciding at that time which network interface is best to use.bind()
will not report an error in that situation.setsockopt(.... SOL_SOCKET, SO_REUSEADDR, ...)
应该可以解决您的问题。请参阅 setsockopt(2) 和 < a href="http://www.kernel.org/doc/man-pages/online/pages/man7/socket.7.html" rel="nofollow">socket(7)
(至于为什么这第二个
bind
实际上成功了,不知道......实际上这也应该已经失败了)setsockopt(.... SOL_SOCKET, SO_REUSEADDR, ...)
should fix your problem.See setsockopt(2) and socket(7)
(as to why the second
bind
actually succeeds, no idea... actually this should already fail too)