PYTHON3 Multicast Communication Programming Implementation Tutorial (sender + Receiver)

Source: Internet
Author: User

I. Description of the 1.1 Standard multicast interpretation

Communication is divided into unicast, multicast (that is, multicast), broadcast three kinds of ways

Unicast means that the IP packet is transmitted by the router to the only device specified by the destination IP after the sender is sent, for example, you are now communicating with the Web server as a unicast form

Broadcast refers to the way that IP packets are sent by the router to all devices connected to it after the sender sends them

Multicast means that after the sender sends, the IP packet is sent by the router to the destination IP corresponding to the multicast group name of the communication form of all hosts

1.2 People understand multicast interpretation

For the standard multicast interpretation, the explanation seems to be clear, but there are many problems in the specific technology. For example, do I send a packet to a multicast address that corresponds to a physical device? If it's not a physical device, then who is based on what hosts the packets are sent to, and so on.

The following points are summed up in the context of each data and self-test:

1) Write the sender: The multicast packet is and only the destination IP is the multicast reserved address of the UDP packet, the difference with the normal UDP packet is only the destination IP is multicast reserved IP

2) Send packet host: Network card after seeing the destination IP is multicast reserved IP, automatically change the destination MAC address to the multicast MAC address and send it to each port

3) Switch: After receiving the packet, the switch realizes through the destination MAC address that this is a multicast packet, modifies the source MAC for its own Mac, keeps the destination MAC for the multicast Mac unchanged to its various ports are sent out (the switch to the multicast packet processing and broadcast packets should be the same, Or, for switches, only unicast packets and broadcast packets)

4) Router: After receiving the packet, the router realizes through the destination MAC address or destination IP address that this is a multicast packet, modifies the source MAC for its own Mac, keeps the destination MAC for the multicast Mac unchanged, keeps the source IP intact, keeps the destination IP for multicast reserved IP unchanged, according to the routing table similar to "Multicast Group Address Table" sends data packets to one or more ports that match the destination IP

5) Receive packet host: Receive packet host to receive the packet sent by the sending host, first he will (to the router description) to join the sender sent to the multicast group, and then he will start a local process to listen to the sender's port

6) multicast requires hardware support, some routers do not support multicast, it is intuitive to see if the global implementation of multicast that Maintenance "Multicast Group Address Table" will bring a lot of burden to the router large vendors should also not be very willing to support multicast; in other words, multicast can be implemented on the WAN, But in fact, usually only in the local area network (CAN) use.

Examples of communication are as follows:

Sender s (assuming that the multicast address is 234.2.2.2, using a multicast port of 23456)----The sender sends a UDP packet to 234.2.2.2:23456 Packet1

Receiver R1 (assuming its IP address is 192.168.220.128)----The first step is to join the multicast group (234.2.2.2) through setsockopt; the second step is to start the process monitoring 192.168.220.128:23456

Receiver R2 (assuming its IP address is 192.168.220.129)----The first step is to join the multicast group (234.2.2.2) through setsockopt; the second step is to start the process monitoring 192.168.220.129:23456

The final effect----a UDP packet sent to 234.2.2.2:23456 by the sender, R1 23456 Port received a copy of the PACKET1,R2 23456 Port received a copy of the Packet1

1.3 Who is the server-side cause of confusion

I have been using "sender" and "receiver" in front of me instead of "Server side" and "Client" because "server side" and "client" are prone to confusion in multicast.

In our general socket programming is the service side to bind, but in the multicast is in turn, the client (receiver) to bind, and the sender (server) is not to bind (note is not necessary, not can not, you have to bind is also possible, Bind and not bind are just the difference between using a fixed port or using a random port).

Some small partners are aware of this problem, in order to be consistent with the habit, so the sender is called the client directly, the receiver is called the server side.

In fact, this is not suitable for the first high school computer class scene as an example: the Teacher control all computer display teacher computer operation, at this time as the sender of the teacher computer from the cognitive should really be the service side rather than the client.

If you read for a long time do not understand what is said here, do not care, remember to use "sender" and "receiver" in the multicast, less use of "server" and "client" is right.

Second, the program implementation of 2.1 program code

Sender Code:

Import TimeImportSocket#Multicast group IP and PortsMCAST_GROUP_IP ='234.2.2.2'Mcast_group_port= 23456defsender ():#Create a Send socket, no difference from normal UDP packetsSend_sock =Socket.socket (socket.af_inet, socket. SOCK_DGRAM, Socket. IPPROTO_UDP)#send a message every 10 seconds     whileTrue:message="This message send via Mcast!"        #sending the notation and normal UDP packets is still completely different.        #guess it's only possible that the NIC itself automatically sets the destination MAC address to the multicast MAC address after it recognizes that the destination IP is the multicast addresssend_sock.sendto (Message.encode (), (Mcast_group_ip, mcast_group_port))Print(f'{time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ())}: Message Send finish') Time.sleep (10)if __name__=="__main__": Sender ()

Recipient code:

ImportstructImport TimeImportSocket#Multicast group IP and PortsMCAST_GROUP_IP ='234.2.2.2'Mcast_group_port= 23456defreceiver ():#create a Receive socket, no difference from normal UDP packetsSock =Socket.socket (socket.af_inet, socket. SOCK_DGRAM, Socket. IPPROTO_UDP)#get local IP addressLOCAL_IP =Socket.gethostbyname (Socket.gethostname ())#Listening Port , has been tested can be directly bind 0.0.0.0; but be careful not to bind 127.0.0.1 or else the multicast packets sent by other machines will not be received.Sock.bind ((local_ip, mcast_group_port))#join a multicast groupMreq = Struct.pack ("=4SL", Socket.inet_aton (MCAST_GROUP_IP), socket. Inaddr_any) sock.setsockopt (socket. Ipproto_ip,socket. Ip_add_membership,mreq)#allow port reuse, see a lot of tutorials have no idea what the meaning is, I directly comment out here    #sock.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)    #set non-blocking, see a lot of tutorials have no idea what is the use, I directly comment out here    #sock.setblocking (0)     whileTrue:Try: message, addr= Sock.recvfrom (1024)            Print(f'{time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ())}: Receive data from {addr}: {Message.decode ()}')        except :            Print("While receive message error occur")if __name__=="__main__": Receiver ()

2.2 Run

Sent by:

Receiver run:

Reference:

19285363

74938534?locationnum=10&fps=1

Http://blog.sina.com.cn/s/blog_69c81c3e0102x9pm.html

PYTHON3 Multicast Communication Programming Implementation Tutorial (sender + Receiver)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.