在C中关闭侦听TCP套接字

时间:2022-11-21 07:37:21

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端口的套接字,并且某些客户端已连接。当在C中发出sock_close(fd)并尝试在同一端口再次绑定时,绑定失败。在“netstat -plutnoa”上可以看到一些TIME_WAIT状态,例如:

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?

那么如何才能正确断开服务器套接字并立即在同一端口重新连接?

1 个解决方案

#1


8  

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.

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

#1


8  

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.

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