Python UDP广播未发送 [英] Python UDP Broadcast not sending

查看:226
本文介绍了Python UDP广播未发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Python程序到两个LabView程序的UDP广播.我似乎无法发送广播,并且不确定套接字初始化错误在哪里,广播似乎很简单?据我所知,其他PC没有接收到任何数据.另外,将来我将需要该程序从其他PC接收数据.看来这不应该使事情复杂化,但我的每一步都变得很复杂!

I am trying to UDP broadcast from a Python program to two LabView programs. 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. Also, I will need this program to receive data back from the other PC's in the future. It seems like that shouldn't complicate things but every step of the way has been complicated for me!

背景:我的软件经验为零,这只是我在工作中分配的.任何帮助表示赞赏.代码如下. Python 2.7.

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.

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)

推荐答案

您不需要connect()到UDP套接字,而是:

You do not need to connect() to a UDP socket, instead:

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

这似乎对我有用:

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))

在另一台机器上,我运行了tcpdump:

On another machine I ran 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....

您可以在有效载荷中看到文本.以及广播以太网和IP dst地址.

You can see the text in the payload. As well as the broadcast Ethernet and IP dst addrs.

这篇关于Python UDP广播未发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆