【发布时间】:2011-08-18 00:36:51
【问题描述】:
我有一个 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.
【问题讨论】:
-
对将其移至 SO 有任何反对意见吗?它最终成为一个完全编程问题,所以它可能更有意义
-
完全没有,我只是在这里发布这个,因为我正在考虑一个Linux命令来关闭套接字,我同意它的编程材料。也许可以更改标题以反映它是一个 Python 程序。
-
@Mr. Shickadance 已迁移,如果您认为有必要,您将不得不改写标题。
标签: python linux sockets networking tcp