How do you send and receive UDP multicast in Python? Is there a standard library to do so?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Multicast traffic is no different than regular UDP except for the IP address. Take a look at the standard socket library. You may be able to find something that builds on socket and is easier to use.
tolomea's answer worked for me. I hacked it into socketserver.UDPServer too:
Multicast sender that broadcasts to a multicast group:
Multicast receiver that reads from a multicast group and prints hex data to the console:
Better use:
instead of:
because, if you want to listen to multiple multicast groups on the same port, you'll get all messages on all listeners.
Have a look at py-multicast. Network module can check if an interface supports multicast (on Linux at least).
Perhaps problems with not seeing IGMP, were caused by an interface not supporting multicast?
In order to Join multicast group Python uses native OS socket interface. Due to portability and stability of Python environment many of socket options are directly forwarded to native socket setsockopt call. Multicast mode of operation such as joining and dropping group membership can be accomplished by
setsockopt
only.Basic program for receiving multicast IP packet can look like:
Firstly it creates socket, binds it and triggers triggers multicast group joining by issuing
setsockopt
. At very end it receives packets forever.Sending multicast IP frames is straight forward. If you have single NIC in your system sending such packets does not differ from usual UDP frames sending. All you need to take care of is just set correct destination IP address in
sendto()
method.I noticed that lot of examples around Internet works by accident in fact. Even on official python documentation. Issue for all of them are using struct.pack incorrectly. Please be advised that typical example uses
4sl
as format and it is not aligned with actual OS socket interface structure.I will try to describe what happen underneath the hood when exercising setsockopt call for python socket object.
Python forwards setsockopt method call to native C socket interface. Linux socket documentation (see
man 7 ip
) introduces two forms ofip_mreqn
structure for IP_ADD_MEMBERSHIP option. Shortest is form is 8 bytes long and longer is 12 bytes long. Above example generates 8 bytesetsockopt
call where fist for bytes definesmulticast_group
and secondinterface_ip
.