UDP广播案例,一端发送,多端接受:

发送端:

# UDP广播案例
from socket import *
from time import sleep
# 设定目标地址
dest=('176.215.122.255',6666)
s=socket(AF_INET,SOCK_DGRAM)
s.setsockopt(SOL_SOCKET,SO_BROADCAST,1)
data='本人到此一游'
while True:
    sleep(2)
    s.sendto(data.encode(),dest)
s.close()

接收端:

# udp广播案例
from socket import *
s=socket(AF_INET,SOCK_DGRAM)
# 设置套接字
s.setsockopt(SOL_SOCKET,SO_BROADCAST,1)
# 选择一个接收地址
s.bind(('0.0.0.0',9821))
while True:
    try:
        msg,addr=s.recvfrom(1024)
        print('from %s bg %s'% (addr,msg.decode()))
    except KeyboardInterrupt:
        break
    except Exception as e:
        print(e)
s.close()

小生不才,请多多指教!!!