listen called on socket more than once — expected behavior?

◇◆丶佛笑我妖孽 提交于 2021-02-07 09:02:28

问题


I noticed something odd while working with a simple C-based server program on my Linux (4.10.3) system. I accidentally ended up calling listen() twice on a socket (from the server process) I had called bind() on earlier. I noticed that both the listen calls succeeded without any errors. In fact, it doesn't seem to matter how many calls to listen I make, all calls to listen succeed.

I was expecting all the calls to listen after the first one to fail with EADDRINUSE. Am I missing something? Linux/POSIX man pages don't seem to say anything about this. I did find one reference about this behavior on the following web-page:

https://www.mkssoftware.com/docs/man3/listen.3.asp

An application may call listen() more than once on the same socket. This has the effect of updating the current backlog for the listening socket. Should there be more pending connections than the new backlog value, the excess pending connections are reset and dropped.

It's unclear to me if this also applies to Linux. And so my question is: what happens when listen is called on the same socket more than once from the same process? (Apparently there are no visible side-effects in user space, but does the Linux kernel do something special in kernel space?)

Thanks.


回答1:


The Linux kernel adjusts the backlog queue length using the new backlog value, but only for future connection requests. It does not discard any pending connections already in the queue.

Second and subsequent calls to listen() have no other effect, and will not fail unless the socket is of the wrong type (not SOCK_STREAM), or is in the wrong state (already connected to a specific peer, or is already in the process of being closed).



来源:https://stackoverflow.com/questions/43078649/listen-called-on-socket-more-than-once-expected-behavior

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!