RODY/app/utils/UDPSender.py
552068321@qq.com 6f7de660aa first commit
2022-11-04 17:37:08 +08:00

33 lines
941 B
Python

#!/usr/bin/python3
# coding= utf-8
import time
import struct
import socket
# 本机信息
host_ip = socket.gethostname()
host_port = 6501
# 组播组IP和端口
mcast_group_ip = '239.255.255.252'
mcast_group_port = 5678
def sender():
send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
send_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
send_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
send_sock.bind((host_ip, host_port))
# 设置存活时长
ttl_bin = struct.pack('@i', 255)
send_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin)
while True:
data = '12345 english 汉字#测试'
send_sock.sendto(str(data).encode('utf-8'), (mcast_group_ip, mcast_group_port))
print(f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}: send finish.')
time.sleep(10)
if __name__ == "__main__":
sender()