Skip to content

Instantly share code, notes, and snippets.

@HelloZeroNet
Last active February 25, 2018 13:55
Show Gist options
  • Save HelloZeroNet/f19732467b731cf792466687f84c2aad to your computer and use it in GitHub Desktop.
Save HelloZeroNet/f19732467b731cf792466687f84c2aad to your computer and use it in GitHub Desktop.
UDP broadcast test
import gevent.monkey
import time, sys, socket, struct
gevent.monkey.patch_all(sys=True)
broadcast_port = 11112
def getMyIps():
local_ips = []
# get local ip using UDP and a broadcast address
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# Not using <broadcast> because gevents getaddrinfo doesn't like that
# using port 1 as per hobbldygoop's comment about port 0 not working on osx:
# https://github.com/sirMackk/ZeroNet/commit/fdcd15cf8df0008a2070647d4d28ffedb503fba2#commitcomment-9863928
s.connect(('239.255.255.250', 1))
local_ips.append(s.getsockname()[0])
# Get ip by using UDP and a normal address (google dns ip)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 0))
local_ips.append(s.getsockname()[0])
except:
pass
# Get ip by '' hostname . Not supported on all platforms.
try:
local_ips += socket.gethostbyname_ex('')[2]
except:
pass
# Delete duplicates
local_ips = list(set(local_ips))
# Probably we looking for an ip starting with 192
local_ips = sorted(local_ips, key=lambda a: a.startswith("192"), reverse=True)
return local_ips
s_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
def server():
global s_sock
s_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if hasattr(socket, 'SO_REUSEPORT'):
s_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
s_sock.bind(('', broadcast_port))
print 'start listening service on udp port %s...' % broadcast_port
while True :
message, address = s_sock.recvfrom(8192)
if message.startswith("echo:"):
print "Echo request from %s: %s" % (address, message)
s_sock.sendto("Your message was %s" % message, (address[0], broadcast_port))
else:
print "Message from %s: %s" % (address, message)
gevent.spawn(server)
time.sleep(0.1)
while 1:
message = raw_input("> ")
if not message:
continue
if message == "q":
break
my_ips = getMyIps()
addr = ("255.255.255.255", 11112)
print "Broadcasting using %s" % my_ips
for my_ip in my_ips:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.bind((my_ip, 0))
sock.sendto(message, addr)
time.sleep(0.3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment