简体   繁体   English

Python UDP广播不发送

[英]Python UDP Broadcast not sending

I am trying to UDP broadcast from a Python program to two LabView programs. 我正在尝试从Python程序到两个LabView程序的UDP广播。 I cannot seem to get the broadcast to send and I am not sure where my socket initialization is wrong, broadcasting seems simple enough?? 我似乎无法播放广播,我不知道我的套接字初始化是错误的,广播似乎很简单? As far as I can see, there is no data being received by the other PC's. 据我所知,其他PC没有收到任何数据。 Also, I will need this program to receive data back from the other PC's in the future. 此外,我将需要此程序以便将来从其他PC接收数据。 It seems like that shouldn't complicate things but every step of the way has been complicated for me! 这似乎不应该让事情变得复杂,但对我而言,每一步都很复杂!

Background: I have zero software experience, this is just something I was assigned at work. 背景:我没有软件经验,这只是我在工作中分配的东西。 Any help is appreciated. 任何帮助表示赞赏。 Code is below. 代码如下。 Python 2.7. Python 2.7。

from threading import Thread  
import time  
from socket import *  

cs = socket(AF_INET, SOCK_DGRAM)  
cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)  
cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)  
cs.connect(('<broadcast>', 5455)) 


while 1:
    cmd = int(raw_input('send: '))
    if (cmd == 1):
        cs.send('1')
    time.sleep(1)

You do not need to connect() to a UDP socket, instead: 您不需要connect()到UDP套接字,而是:

cs.sendto(data, ('255.255.255.255', 5455))

EDIT: This seems to work for me: 编辑:这似乎对我有用:

from socket import *
cs = socket(AF_INET, SOCK_DGRAM)
cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
cs.sendto('This is a test', ('255.255.255.255', 54545))

On another machine I ran tcpdump: 在另一台机器上我运行tcpdump:

tcpdump -i eth1 port 54545 -XX
listening on eth1, link-type EN10MB (Ethernet), capture size 65535 bytes

14:04:01.797259 IP 10.22.4.45.33749 > 255.255.255.255.54545: UDP, length 14
0x0000:  ffff ffff ffff f0de f1c4 8aa6 0800 4500  ..............E.
0x0010:  002a 0000 4000 4011 2c81 0a16 042d ffff  .*..@.@.,....-..
0x0020:  ffff 83d5 d511 0016 fe38 5468 6973 2069  .........8This.i
0x0030:  7320 6120 7465 7374 0000 0000            s.a.test....

You can see the text in the payload. 您可以在有效负载中看到该文本。 As well as the broadcast Ethernet and IP dst addrs. 以及广播以太网和IP dst添加器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM