python udp广播_Python UDP广播未发送

本文作者分享了在Python中使用UDP进行广播的问题,探讨了如何正确设置socket选项以实现广播,并提供了通过tcpdump观察到的接收数据实例。重点在于解决连接问题和正确发送广播数据的方法,为初学者提供实用指导。
摘要由CSDN通过智能技术生成

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!

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(('', 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:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值