gpt4 book ai didi

python - 为什么我不能在 Python 中接收 UDP 数据包?

转载 作者:行者123 更新时间:2023-11-28 16:39:31 26 4
gpt4 key购买 nike

我正在尝试通过 UDP 连接 A/V 设备。我向本地广播 192.168.0.255 发送了一个数据包,它以有关设备的信息进行响应。我可以验证它是否适用于 Wireshark。但是,我从未在 Python 中得到响应,它就在那里:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #Internet, UDP
s.bind(('', 64000))
#s.sendto('0:0',('192.168.0.255',63630))
s.connect(('192.168.0.255',63630));
s.send('0:0')
#s.listen(1)
data,addr = s.recvfrom(1024)
print data
print 'from', addr

我将它从 64000(随机端口)发送到 63630 端口,所以在发送它的 64000 端口进行绑定(bind)和接收,然后再发送回,应该可以,对吗?我错过了一步吗?

最佳答案

打开SO_BROADCAST选项发送广播消息:

s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

同时替换以下内容

s.connect(('192.168.0.255',63630))
s.send('0:0')

与:

s.sendto('0:0', ('192.168.0.255',63630))

根据 Linux connect(2) 联机帮助页:

If the socket sockfd is of type SOCK_DGRAM then addr is the address to which datagrams are sent by default, and the only address from which datagrams are received.

根据 MSDN - connect (Windows Sockets) :

For a connectionless socket (for example, type SOCK_DGRAM), the operation performed by connect is merely to establish a default destination address that can be used on subsequent send/WSASend and recv/WSARecv calls. Any datagrams received from an address other than the destination address specified will be discarded.

关于python - 为什么我不能在 Python 中接收 UDP 数据包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21360537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com