From a02d0795af092ac6a0260d4e7bdfa1c6c0a4d0ca Mon Sep 17 00:00:00 2001 From: mmuravytskyi Date: Sat, 5 Jun 2021 09:12:30 +0200 Subject: [PATCH] Multicast: client and server --- config.py | 2 ++ multicast_client.py | 40 ++++++++++++++++++++++++++++++++++++++++ multicast_server.py | 29 +++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+) create mode 100644 config.py create mode 100644 multicast_client.py create mode 100644 multicast_server.py diff --git a/config.py b/config.py new file mode 100644 index 0000000..5872a32 --- /dev/null +++ b/config.py @@ -0,0 +1,2 @@ +MULTICAST_PORT = 10000 +MULTICAST_IP = '224.0.0.1' \ No newline at end of file diff --git a/multicast_client.py b/multicast_client.py new file mode 100644 index 0000000..8481557 --- /dev/null +++ b/multicast_client.py @@ -0,0 +1,40 @@ +import socket +import struct +import sys +import config + +message = 'SERVER DISCOVERY' +multicast_group = (config.MULTICAST_IP, config.MULTICAST_PORT) + +# 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 "%s"' % message) + sent = sock.sendto(bytes(message, encoding='utf-8'), 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 "%s" from %s' % (data, server)) + +finally: + print('closing socket') + sock.close() diff --git a/multicast_server.py b/multicast_server.py new file mode 100644 index 0000000..b35357b --- /dev/null +++ b/multicast_server.py @@ -0,0 +1,29 @@ +import socket +import struct +import sys +import config + +server_address = ('', config.MULTICAST_PORT) + +# 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. +mcast_group = socket.inet_aton(config.MULTICAST_IP) +mreq = struct.pack('4sL', mcast_group, socket.INADDR_ANY) # listen on all interfaces `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 %s bytes from %s' % (len(data), address)) + print(data) + + print('sending acknowledgement to', address) + sock.sendto(bytes('ack', encoding='utf-8'), address)