Skip to content

Instantly share code, notes, and snippets.

@cry
Forked from ninedraft/README.md
Created September 4, 2018 01:45
Show Gist options
  • Save cry/9e435d54cbe95fe9fddc2e0596409265 to your computer and use it in GitHub Desktop.
Save cry/9e435d54cbe95fe9fddc2e0596409265 to your computer and use it in GitHub Desktop.
Python udp broadcast client server example
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
client.bind(("", 37020))
while True:
data, addr = sock.recvfrom(1024)
print("received message: %s"%data)
import socket
import time
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# Set a timeout so the socket does not block
# indefinitely when trying to receive data.
server.settimeout(0.2)
server.bind(("", 44444))
message = b"your very important message"
while True:
server.sendto(message, ('<broadcast>', 37020))
print("message sent!")
time.sleep(1)
@umangshrestha
Copy link

hi,

There is a small issue in client.py.

  1. line 7: the sock should be client.
  2. line 8: It's better to decode data before printing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment