#!/usr/bin/python3 # coding= utf-8 import socket import sys import struct import json # 本机信息 import time host_ip = socket.gethostbyname(socket.gethostname()) # 组播组IP和端口 mcast_group_ip = '224.1.1.1' mcast_group_port = 2234 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) data2 = json.loads(data) # 若组播数据不正确 if len(data2) < 3: return 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()