broadcast02.py

# ==========================================================
# Send UDP broadcast packets
#
# From: stackoverflow.com/questions/22878625/
#       receiving-broadcast-packets-in-python
# 
# modified by me
# ==========================================================

import sys, time
from socket import *

MYPORT = 10000

# ---------------------------------------------------------
# --- running Python 3?
# ---------------------------------------------------------

def RunningPython3():
    ##print(sys.version_info)
    if sys.version_info[0] == 3:
        return True
    return False

# ---------------------------------------------------------
# --- main
# ---------------------------------------------------------

py3 = RunningPython3()

print('port    = {}'.format(MYPORT))
print('Python3 = {}'.format(py3))

s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', 0))
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)

# --- loop sending messages

while True:
    data = repr(time.time())
    print(data)

    if py3:
       # Python 3
       s.sendto(data.encode(), ('<broadcast>', MYPORT))
    else:
       # python 2
       s.sendto(data,('<broadcast>', MYPORT))

    time.sleep(2)