python - 如何关闭被杀死的程序打开的套接字?

我有一个 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))

https://stackoverflow.com/questions/5875177/

相关文章:

linux - qstat 和长作业名称

linux - 在家学习内核黑客和嵌入式开发?

c - Linux内核代码中的 "EXPORT_SYMBOL"是什么意思?

linux - 使用 Linux 加载程序时 ldconfig 错误 :"is not a symb

linux - 应用程序如何在运行时解析为不同版本的共享库?

linux - cron 如何在内部安排作业?

linux - 跨多台计算机管理用户配置文件

c - 为什么在 Linux 中使用 select

linux - RealUID,保存的 UID,有效的 UID。这是怎么回事?

python - 带有隐藏窗口的跨平台子进程