Skip to content

Commit

Permalink
Multicast: client and server
Browse files Browse the repository at this point in the history
  • Loading branch information
mmuravytskyi committed Jun 5, 2021
1 parent 5267425 commit a02d079
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
2 changes: 2 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
MULTICAST_PORT = 10000
MULTICAST_IP = '224.0.0.1'
40 changes: 40 additions & 0 deletions multicast_client.py
Original file line number Diff line number Diff line change
@@ -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()
29 changes: 29 additions & 0 deletions multicast_server.py
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit a02d079

Please sign in to comment.