Skip to content

Instantly share code, notes, and snippets.

@rubenhorn
Created June 7, 2020 09:44
Show Gist options
  • Save rubenhorn/d11e47cedba9e7921ac799310aad9ba1 to your computer and use it in GitHub Desktop.
Save rubenhorn/d11e47cedba9e7921ac799310aad9ba1 to your computer and use it in GitHub Desktop.
Simple UDP broadcasting demo
import socket
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--mode', choices=['sender', 'receiver'], required=True)
arguments = parser.parse_args()
is_sender = arguments.mode == 'sender'
receiver_port = 1234
receive_size = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.settimeout(0.2)
if is_sender:
payload_bytes = b'Hello world!'
print('sending "{}"'.format(payload_bytes))
sock.sendto(payload_bytes, ('<broadcast>', receiver_port))
else:
sock.bind(('', receiver_port))
print('receiving...')
while True:
try:
pass
data, addr = sock.recvfrom(receive_size)
print('got "{}" from {}'.format(data, addr))
break
except socket.timeout:
pass # Handle timeout, stop with Ctrl + C
print('end.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment