ruby udp broadcast simple example

Here’s a simpler version sender  (client):

require 'socket'
addr = ['<broadcast>', 33333]# broadcast address
#addr = ('255.255.255.255', 33333) # broadcast address explicitly [might not work ?]
#addr = ['127.0.0.255', 33333] # ??
UDPSock = UDPSocket.new
UDPSock.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true)
data = 'I sent this'
UDPSock.send(data, 0, addr[0], addr[1])
UDPSock.close

Receiver (server):


require 'socket'
addr = ['0.0.0.0', 33333]  # host, port
BasicSocket.do_not_reverse_lookup = true
# Create socket and bind to address
UDPSock = UDPSocket.new
UDPSock.bind(addr[0], addr[1])
data, addr = UDPSock.recvfrom(1024) # if this number is too low it will drop the larger packets and never give them to you
puts "From addr: '%s', msg: '%s'" % [addr[0], data]
UDPSock.close

4 thoughts on “ruby udp broadcast simple example

Leave a Reply

Your email address will not be published. Required fields are marked *


9 × three =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>