Skip to main content
 首页 » 编程设计

python之发送到未监听的ip/port时,Python的UDP崩溃

2025年02月15日30bonelee

如果您将UDP数据包发送到未监听的随机ip /端口,python是否会关闭发送该数据包的服务器(导致崩溃)?

我是在做错什么还是错误?

问题示例:

import socket 
 
# Launch the server 
try: 
    Sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    Sock.bind(("127.0.0.1", 25565)) 
except: 
    print("Failed to launch server") 
 
# Send a packet to a random (closed) place 
# Comment out this line to prevent error 
Sock.sendto(b'', ("127.0.0.1", 4623)) 
 
 
while True: 
    # Wait for data 
    print("Listening for data") 
    data, addr = Sock.recvfrom(1024) 

错误:

line 18, in data, addr = Sock.recvfrom(1024) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

请您参考如下方法:

即使在UDP套接字上,recvfrom也会失败。例如,如果先前的发送尝试将数据包发送到没有人正在侦听端口的系统,而接收方发送回无法到达的ICMP,则可以执行此操作。

您的服务器仅崩溃是因为您不希望recvfrom失败,即,没有像使用bind那样将其包装到try块中。如果使用此类块捕获了预期的错误,则服务器不会崩溃,但可以正确处理该错误。