[python]套接字 recvfrom() 在尝试在 python 中捕获 UDP 或多播数据时挂起/阻塞
· 收录于 2023-11-21 05:04:06 · source URL
问题详情
首先,我想表明我的静态IP 10.10.10.88接口正在接收数据,所以我不明白这可能是防火墙问题: Wireshark 中的数据包
当我运行以下代码时,Wireshark 未运行。
我的程序在调用 recfrom()
时挂起。下面是查找传统 UDP 广播的示例,如上面从 IP 10.10.10.120 到 255.255.255.255 端口 2222 的链接图像所示:
import socket
# IP address associated with the network interface
ip_address = '10.10.10.88'
port = 2222 # port I'm listening on
# Create a UDP socket and bind it to the IP address
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_socket.bind((ip_address, port))
print(f"Listening for UDP packets on {ip_address}:{port}")
try:
while True:
print('test1')
data, addr = udp_socket.recvfrom(1024)
print('test2')
# Print the received packet data as hexadecimal
print(f"Received packet from {addr}: {data.hex()}")
except KeyboardInterrupt:
print("Capture stopped by user (Ctrl+C).")
udp_socket.close()
输出如下:
Listening for UDP packets on 10.10.10.88:2222
test1
。它只是永远挂着。我甚至不能使用 Ctrl+C 来摆脱它——我必须杀死这个过程。
当我尝试查看从 IP 10.10.10.101 到 238.1.0.101 端口 50101 的组播数据包(请参阅上面的 Wireshark 片段)时,我遇到了以下代码的相同问题:
import socket
import struct
# Specify the multicast group address and port
multicast_group = '238.1.0.101'
multicast_port = 50101
# Create a UDP socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set the socket to allow reuse of the address (in case it's used by other processes)
udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind the socket to the specified multicast address and port
udp_socket.bind(('', multicast_port))
# Set the IP_ADD_MEMBERSHIP option to join the multicast group
mreq = struct.pack('4sl', socket.inet_aton(multicast_group), socket.INADDR_ANY)
udp_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
print(f"Listening for multicast packets on {multicast_group}:{multicast_port}")
try:
while True:
print('test1')
data, addr = udp_socket.recvfrom(1024)
print('test2')
# Print the received packet data as hexadecimal
print(f"Received packet from {addr}: {data.hex()}")
except KeyboardInterrupt:
print("Capture stopped by the user (Ctrl+C).")
udp_socket.close()
输出:
Listening for multicast packets on 238.1.0.101:50101
test1
同样,它挂起,我无法按 Ctrl+C 退出它。
请帮帮我 .
最佳回答
暂无回答