Skip to content

Instantly share code, notes, and snippets.

@zhanglongqi
Last active June 30, 2017 10:32
Show Gist options
  • Save zhanglongqi/8ff8589e93ec9d453ec05098469618ed to your computer and use it in GitHub Desktop.
Save zhanglongqi/8ff8589e93ec9d453ec05098469618ed to your computer and use it in GitHub Desktop.
broadcast a message in the local network
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
longqi 30/Jun/17 16:36
Description:
"""
from socket import socket, AF_INET, SOCK_DGRAM, SOL_SOCKET, SO_BROADCAST, SO_REUSEADDR
from time import time, ctime
s = socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
s.bind(('', 12345))
while True:
m = s.recvfrom(1024)
print(ctime(time()), m)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
longqi 30/Jun/17 16:38
Description:
To broadcast the message to the network
Thanks for the question and the answers https://stackoverflow.com/questions/12607516/python-udp-broadcast-not-sending
"""
from socket import *
from time import sleep
s = socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
count = 0
while True:
s.sendto(bytes('Message No. ' + str(count), encoding='utf8'), ('<broadcast>', 12345))
sleep(1)
count += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment