在 Python 中接收广播数据包

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22878625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:52:13  来源:igfitidea点击:

Receiving Broadcast Packets in Python

pythonsocketsudpbroadcast

提问by nitish712

I have the following code which sends a udppacket that is broadcasted in the subnet.

我有以下代码发送udp在子网中广播的数据包。

from socket import *
s=socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
s.sendto('this is testing',('255.255.255.255',12345))

The following code is for receiving the broadcast packet.

以下代码用于接收广播数据包。

from socket import *
s=socket(AF_INET, SOCK_DGRAM)
s.bind(('172.30.102.141',12345))
m=s.recvfrom(1024)
print m[0]

The problem is that its not receiving any broadcast packet. However, it is successfully receiving normal udp packets sent to that port.

问题是它没有收到任何广播数据包。但是,它成功接收发送到该端口的正常 udp 数据包。

My machine was obviously receiving the broadcast packet, which I tested using netcat.

我的机器显然正在接收广播数据包,我使用netcat.

$ netcat -lu -p 12345                                             
this is testing^C

So, where exactly is the problem?

那么,问题究竟出在哪里呢?

采纳答案by John Zwinck

Try binding to the default address:

尝试绑定到默认地址:

s.bind(('',12345))

回答by Abraham Philip

I believe the solution outlined in the accepted answer solves the issue, but not in exactly the right way. You shouldn't use the normal interface IP, but the broadcast IP which is used to send the message. For example if ifconfig is:

我相信接受的答案中概述的解决方案解决了这个问题,但不是以完全正确的方式。您不应该使用普通的接口 IP,而应该使用用于发送消息的广播 IP。例如,如果 ifconfig 是:



inet 地址:10.0.2.2 Bcast:10.0.2.255 掩码:255.255.255.0

那么服务器应该使用 s.bind(('10.0.2.255',12345)),而不是 10.0.2.2(在 OP 的情况下,他应该使用 255.255.255.255)。接受的答案有效的原因是因为“ ”告诉服务器接受来自所有地址的数据包,同时指定 IP 地址并对其进行过滤。





' ' 是锤子,指定正确的广播地址是手术刀。在许多情况下,虽然可能不是 OP,但为了安全起见,服务器仅侦听指定的 IP 地址很重要(例如,您只想接受来自专用网络的请求 - 上面的代码也将接受来自任何外部网络的请求)如果没有别的目的。

回答by MinhNV

s=socket(AF_INET, SOCK_DGRAM)
s.bind(('',1234))
while(1):
    m=s.recvfrom(4096)
    print 'len(m)='+str(len(m))
    print 'len(m[0])='+str(len(m[0]))    
    print m[0]

    print 'len(m[1])='+str(len(m[1]))    
    print m[1]