如何关闭被杀死的程序打开的套接字? [英] How to close a socket left open by a killed program?
问题描述
我有一个 Python 应用程序,它打开一个简单的 TCP 套接字以与单独主机上的另一个 Python 应用程序进行通信.有时程序会出错,或者我会直接杀死它,在任何一种情况下,套接字可能会在未知的时间内保持打开状态.
下次运行程序时出现此错误:
socket.error: [Errno 98] 地址已被使用
现在程序总是尝试使用同一个端口,所以它看起来好像仍然是打开的.我检查并确定该程序没有在后台运行,但我的地址仍在使用中.
那么,我如何手动(或以其他方式)关闭套接字/地址,以便我的程序可以立即重新使用它?
更新
根据 Mike 的回答,我查看了 socket(7)
页面并查看了 SO_REUSEADDR:
SO_REUSEADDR指示用于验证 bind(2) 调用中提供的地址的规则应该允许重用本地地址.对于 AF_INET 套接字,这意味着套接字可以绑定,除非有一个绑定到该地址的活动侦听套接字.当聆听——ing 套接字绑定到具有特定端口的 INADDR_ANY 那么就不可能绑定到此端口以获取任何本地地址.参数是一个整数布尔标志.
假设你的 socket 名为 s
... 你需要在服务器端设置 socket.SO_REUSEADDR
绑定到接口之前的套接字...这将允许您立即重新启动 TCP 服务器...
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)s.bind((ADDR, PORT))
I have a Python application which opens a simple TCP socket to communicate with another Python application on a separate host. Sometimes the program will either error or I will directly kill it, and in either case the socket may be left open for some unknown time.
The next time I go to run the program I get this error:
socket.error: [Errno 98] Address already in use
Now the program always tries to use the same port, so it appears as though it is still open. I checked and am quite sure the program isn't running in the background and yet my address is still in use.
SO, how can I manually (or otherwise) close a socket/address so that my program can immediately re-use it?
Update
Based on Mike's answer I checked out the socket(7)
page and looked at 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.
Assume your socket is named s
... you need to set socket.SO_REUSEADDR
on the server's socket before binding to an interface... this will allow you to immediately restart a TCP server...
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((ADDR, PORT))
这篇关于如何关闭被杀死的程序打开的套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!