如何关闭被杀死程序打开的套接字? [英] How to close a socket left open by a killed program?

查看:91
本文介绍了如何关闭被杀死程序打开的套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python应用程序,该应用程序打开一个简单的TCP套接字以与单独主机上的另一个Python应用程序进行通信.有时程序会出错,或者我将直接杀死它,并且在任何一种情况下,套接字都可能在未知的时间内保持打开状态.

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?

更新

根据Mike的回答,我签出了socket(7)页并查看了SO_REUSEADDR:

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.

推荐答案

假设您的套接字名为s ...您需要在绑定到接口之前在服务器的套接字上设置socket.SO_REUSEADDR ...这将允许您立即重新启动TCP服务器...

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆