关闭C中的侦听TCP套接字 [英] Closing a listening TCP socket in C
问题描述
假设您有一个侦听TCP端口的套接字,并且某些客户端已连接.当在C中发出sock_close(fd)并尝试在同一端口上再次绑定时,绑定失败.在"netstat -plutnoa"上看到一些TIME_WAIT状态,例如:
Suppose you have a socket listening on a TCP port, and some clients are connected. When one issues sock_close(fd) in C and tries to bind again on the same port, binding fails. Some TIME_WAIT state is seen on the "netstat -plutnoa" such as:
tcp 0 0 127.0.0.1:4567 127.0.0.1:32977 TIME_WAIT - timewait (17.12/0/0)
那么如何正确断开服务器套接字并立即在同一端口上重新连接?
So how one can properly disconnect the server socket and reconnect on the same port immediately?
推荐答案
您要在套接字上使用SO_REUSEADDR
选项.相关的联机帮助页是 socket(7)
.这是其用法的示例. 此问题说明了会发生什么.
You want to use the SO_REUSEADDR
option on the socket. The relevant manpage is socket(7)
. Here's an example of its usage. This question explains what happens.
这篇关于关闭C中的侦听TCP套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!