Created
October 11, 2018 13:39
-
-
Save friek/6c10535b2e43f0e0867ce21b0679a337 to your computer and use it in GitHub Desktop.
Join a multicast group in python and receive data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import socket | |
import sys | |
def main(argv): | |
multicast_group = argv[1] | |
multicast_port = int(argv[2]) | |
interface_ip = argv[3] | |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) | |
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32) | |
sock.bind(('', multicast_port)) | |
sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, | |
socket.inet_aton(multicast_group) + socket.inet_aton(interface_ip)) | |
while True: | |
received = sock.recv(1500) | |
print('Received packet of {0} bytes'.format(len(received))) | |
if __name__ == '__main__': | |
if len(sys.argv) != 4: | |
print("Usage: {0} <group address> <port> <interface ip>".format(sys.argv[0])) | |
sys.exit(1) | |
main(sys.argv) |
The interface IP is the address of your local interface.
0.0.0.0 may work but this may be system dependent. Using 0.0.0.0 while having a route to 224.0.0.0/4 may work too.
oh cheers, brilliant!
Thanks for sharing, added following code
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# On macOS, this next option is particularly useful for multicast
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
before line 13: sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
so that it won't run into error:
OSError: [Errno 48] Address already in use
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
very neat! can I just ask, what is the interface ip and how does it differ from the multicast group argument? thanks!