Created
November 1, 2018 13:21
-
-
Save ardenn/41b2f0db5aa9f0e208257108b05e31d9 to your computer and use it in GitHub Desktop.
Send a message to a multicast group and record the reponses
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
import socket | |
import struct | |
message = b'very important data' | |
multicast_group = ('224.10.10.10', 10000) | |
# Create the datagram socket | |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
# Set a timeout so the socket does not block | |
# indefinitely when trying to receive data. | |
sock.settimeout(0.2) | |
# Set the time-to-live for messages to 1 so they do not | |
# go past the local network segment. | |
ttl = struct.pack('b', 1) | |
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) | |
try: | |
# Send data to the multicast group | |
print('sending {!r}'.format(message)) | |
sent = sock.sendto(message, multicast_group) | |
# Look for responses from all recipients | |
while True: | |
print('waiting to receive') | |
try: | |
data, server = sock.recvfrom(16) | |
except socket.timeout: | |
print('timed out, no more responses') | |
break | |
else: | |
print('received {!r} from {}'.format( | |
data, server)) | |
finally: | |
print('closing socket') | |
sock.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment