dms-client/util/UDP_Receive.py
2022-02-15 15:41:45 +08:00

47 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/python3
# coding= utf-8
import socket
import sys
import struct
# 本机信息
host_ip = socket.gethostbyname(socket.gethostname())
# 组播组IP和端口
mcast_group_ip = '239.255.255.252'
mcast_group_port = 5678
def receiver():
# 建立接收 udp socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# linux能绑定网卡这里绑定组播IP地址不会服错windows没法绑定网卡只能绑定本网卡IP地址
if "linux" in sys.platform:
# 绑定到的网卡名如果自己的不是eth0则修改
nic_name = 0
# 监听的组播地址
sock.setsockopt(socket.SOL_SOCKET, 25, nic_name)
sock.bind((mcast_group_ip, mcast_group_port))
else:
sock.bind((host_ip, mcast_group_port))
# 加入组播组
mq_request = struct.pack("=4sl", socket.inet_aton(mcast_group_ip), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mq_request)
# 设置非阻塞
sock.setblocking(True)
while True:
try:
data, address = sock.recvfrom(4096)
except socket.error as e:
print(f"while receive message error occur:{e}")
else:
print("Receive Data!")
print("FROM: ", address)
print("DATA: ", data.decode('utf-8'))
if __name__ == "__main__":
receiver()