Python:绑定套接字:“地址已在使用中"

编程入门 行业动态 更新时间:2024-10-25 16:21:51
本文介绍了Python:绑定套接字:“地址已在使用中"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对TCP/IP网络上的客户端套接字有疑问.假设我使用

I have a question regarding client socket on TCP/IP network. Let's say I use

try: comSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error, msg: sys.stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(1) try: comSocket.bind(('', 5555)) comSocket.connect() except socket.error, msg: sys.stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(2)

创建的套接字将绑定到端口5555.问题在于结束连接后

The socket created will be bound to port 5555. The problem is that after ending the connection

comSocket.shutdown(1) comSocket.close()

使用wireshark,我看到套接字从两侧用FIN,ACK和ACK闭合,我无法再使用该端口.我收到以下错误:

Using wireshark, I see the socket closed with FIN,ACK and ACK from both sides, I can't use the port again. I get the following error:

[ERROR] Address already in use

我想知道如何立即清除端口,以便下次仍可以使用该端口.

I wonder how can I clear the port right away so that next time I still can use that same port.

comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

setsockopt似乎无法解决问题 谢谢!

setsockopt doesn't seem to be able to resolve the problem Thank you!

推荐答案

在绑定套接字之前尝试使用SO_REUSEADDR套接字选项.

Try using the SO_REUSEADDR socket option before binding the socket.

comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

修改: 我看到您仍然对此感到麻烦.在某些情况下,SO_REUSEADDR将不起作用.如果尝试绑定套接字并重新连接到相同的目的地(启用SO_REUSEADDR),则TIME_WAIT仍然有效.但是,它将允许您连接到其他主机:端口.

I see you're still having trouble with this. There is a case where SO_REUSEADDR won't work. If you try to bind a socket and reconnect to the same destination (with SO_REUSEADDR enabled), then TIME_WAIT will still be in effect. It will however allow you to connect to a different host:port.

想到了几种解决方案.您可以继续重试,直到可以重新获得连接为止.或者,如果客户端启动套接字(而不是服务器)的关闭,那么它应该可以神奇地工作.

A couple of solutions come to mind. You can either continue retrying until you can gain a connection again. Or if the client initiates the closing of the socket (not the server), then it should magically work.

更多推荐

Python:绑定套接字:“地址已在使用中"

本文发布于:2023-08-07 03:36:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1316748.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:已在   绑定   地址   Python   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!