我有一个 Python 应用程序,它打开一个简单的 TCP 套接字以与单独主机上的另一个 Python 应用程序进行通信。有时程序会出错,或者我会直接杀死它,在这两种情况下,套接字都可能会在未知的时间内保持打开状态。
下次我去运行程序时,我得到了这个错误:
socket.error: [Errno 98] Address already in use
现在程序总是尝试使用同一个端口,所以它看起来好像仍然是打开的。我检查并确定程序没有在后台运行,但我的地址仍在使用中。
那么,我如何手动(或以其他方式)关闭套接字/地址,以便我的程序可以立即重用它?
更新
根据 Mike 的回答,我查看了 socket(7)
页面并查看了 SO_REUSEADDR:
SO_REUSEADDR Indicates that the rules used in validating addresses supplied in a bind(2) call should allow reuse of local addresses. For AF_INET sockets this means that a socket may bind, except when there is an active listening socket bound to the address. When the listen‐ ing socket is bound to INADDR_ANY with a specific port then it is not possible to bind to this port for any local address. Argument is an integer boolean flag.
最佳答案
假设您的套接字名为 s
...在绑定(bind)到接口(interface)之前,您需要在服务器的套接字上设置 socket.SO_REUSEADDR
...这将允许您立即重新启动 TCP 服务器...
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((ADDR, PORT))
关于python - 如何关闭被杀死的程序打开的套接字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5875177/