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

标签 python sockets udp python-sockets

我正在尝试通过 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/

相关文章:

c# - 现有连接被远程主机强行关闭

linux - 为什么这个 UDP 客户端/服务器代码不起作用?

c - 查找UDP数据包的源IP/进程

networking - 什么时候使用 UDP 而不是 TCP 合适?

访问递归嵌套 dict 的 Pythonic 方式

客户端断开连接后 C 套接字 TCP 服务器失败

python - SQlite - 为什么我需要提交命令

java - 如何使用基本 Java 套接字停止 ("skip") 等待服务器响应的客户端

python - 是否可以从函数应用程序中的 Azure API 网关调用检索 header ?

python - Pandas 中的多处理错误