Skip to content

Instantly share code, notes, and snippets.

@SubOptimal
Forked from dksmiffs/multicast-rcv.py
Created June 17, 2021 13:09
Show Gist options
  • Save SubOptimal/8ee05fb8643a42003a950a4f4b764327 to your computer and use it in GitHub Desktop.
Save SubOptimal/8ee05fb8643a42003a950a4f4b764327 to your computer and use it in GitHub Desktop.
Python 3 UDP multicast example, with only very minor modifications needed to this guidance: https://stackoverflow.com/a/1794373
# Multicast receiver
# Guidance: https://stackoverflow.com/a/1794373
import socket
import struct
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
IS_ALL_GROUPS = True
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if IS_ALL_GROUPS:
# on this port, receives ALL multicast groups
sock.bind(('', MCAST_PORT))
else:
# on this port, listen ONLY to MCAST_GRP
sock.bind((MCAST_GRP, MCAST_PORT))
mreq = struct.pack('4sl', socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
while True:
print(sock.recv(10240))
# Multicast sender
# Guidance: https://stackoverflow.com/a/1794373
import socket
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
MESSAGE = b'Hello, Multicast!'
# regarding socket.IP_MULTICAST_TTL
# ---------------------------------
# for all packets sent, after two hops on the network the packet will not
# be re-sent/broadcast (see https://www.tldp.org/HOWTO/Multicast-HOWTO-6.html)
MULTICAST_TTL = 2
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL)
sock.sendto(MESSAGE, (MCAST_GRP, MCAST_PORT))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment