Skip to content

Instantly share code, notes, and snippets.

@friek
Created October 11, 2018 13:39
Show Gist options
  • Save friek/6c10535b2e43f0e0867ce21b0679a337 to your computer and use it in GitHub Desktop.
Save friek/6c10535b2e43f0e0867ce21b0679a337 to your computer and use it in GitHub Desktop.
Join a multicast group in python and receive data
#!/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)
@Pompey21
Copy link

Pompey21 commented Nov 4, 2023

very neat! can I just ask, what is the interface ip and how does it differ from the multicast group argument? thanks!

@friek
Copy link
Author

friek commented Nov 4, 2023

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.

@Pompey21
Copy link

oh cheers, brilliant!

@gainskills
Copy link

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