In the project, the Ys Private protocol uses multicast technology, which uses Python to send multicast packets when verifying its security features, and to make a record here.
The multicast server is used to send multicast packets to the multicast group with the following implementation code:
#coding: utf-8, import socket import Timeany='0.0.0.0'Senderport=1501mcast_addr='224.168.2.9'Mcast_port= thesock=Socket.socket (socket.af_inet, socket. SOCK_DGRAM, Socket. IPPROTO_UDP) Sock.bind ((Any,senderport)) #绑定发送端口到SENDERPORT, that is, the send port for this example is 1501sock.setsockopt (socket. IPPROTO_IP, Socket. Ip_multicast_ttl,255) #设置使用多播发送 while 1: Time.sleep (Ten) Sock.sendto ('Hello World', (Mcast_addr,mcast_port)); #将'Hello World'A specified port that is sent to a multicast address, and members belonging to this multicast group can receive this information
The packets captured by Wireshark are as follows:
The multicast client is used to receive multicast packets sent by the multicast server with the following code:
#coding: utf-8, import socket import Timeany='0.0.0.0'mcast_addr='224.168.2.9'Mcast_port= thesock=Socket.socket (socket.af_inet, socket. SOCK_DGRAM, Socket. IPPROTO_UDP) #创建UDP socketsock.setsockopt (socket). Sol_socket,socket. SO_REUSEADDR,1) #允许端口复用 Sock.bind ((any,mcast_port)) #绑定监听多播数据包的端口sock. setsockopt (socket. IPPROTO_IP, Socket. Ip_multicast_ttl,255) #告诉内核这是一个多播类型的socketstatus=sock.setsockopt (socket. Ipproto_ip, #告诉内核把自己加入指定的多播组, the group address is specified by the third parameter of the socket. Ip_add_membership, Socket.inet_aton (MCAST_ADDR)+Socket.inet_aton (any)); Sock.setblocking (0) TS=time.time () while 1: Try: Data, addr= Sock.recvfrom (1024x768) except Socket.error, E:passElse: Print"We got data!"Print"From :", addr Print"DATA:", the data
The key to multicast client code is through (socket. Ip_add_membership) add itself to the multicast group and listen to multicast ports (MCAST_PORT) specified on the multicast server, in addition, the destination address of the multicast server must be a valid multicast address, not a unicast address, such as: (LocalHost/ Inaddr_any/any valid IP).
Python enables the sending and receiving of multicast data