Skip to content

Instantly share code, notes, and snippets.

@ardenn
Created November 1, 2018 13:47
Show Gist options
  • Save ardenn/c4249a7bc944183ea31bf2fdfb48dfbb to your computer and use it in GitHub Desktop.
Save ardenn/c4249a7bc944183ea31bf2fdfb48dfbb to your computer and use it in GitHub Desktop.
Read messages from a multicast socket and send acknowlegements
import socket
import struct
import sys
multicast_group = '224.10.10.10'
server_address = ('', 10000)
# Create the socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind to the server address
sock.bind(server_address)
# Tell the operating system to add the socket to
# the multicast group on all interfaces.
group = socket.inet_aton(multicast_group)
mreq = struct.pack('4sL', group, socket.INADDR_ANY)
sock.setsockopt(
socket.IPPROTO_IP,
socket.IP_ADD_MEMBERSHIP,
mreq)
# Receive/respond loop
while True:
print('\nwaiting to receive message')
data, address = sock.recvfrom(1024)
print('received {} bytes from {}'.format(
len(data), address))
print(data)
print('sending acknowledgement to', address)
sock.sendto(b'ack', address)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment