Skip to content

attempts of obtaining a broadcast address

tora edited this page Jul 5, 2012 · 6 revisions

Using select()

require 'socket'
require 'ipaddr'

def find_broadcast_address host, port
  debug = true
  s = UDPSocket.new
  s.do_not_reverse_lookup = true
  s.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, 1)
  p [ "host = ", host ] if debug
  s.bind "0.0.0.0", port
  (8..31).each do |mask|
    ip = IPAddr.new( "#{host}/#{mask}" ).to_range.max.to_s
    x = "#{ip}"
    p [ "ip = ", x ] if debug
    s.send x, 0, ip, port  
    while select( [s], nil, nil, 0.01 )
      y, addr = s.recvfrom 1500
      p [ "received = ", y, addr ] if debug
      x == y && port == addr[1] && host == addr[3] and return ip
    end
  end
  nil
ensure
  s.close
end

host = IPSocket::getaddress( Socket::gethostname )
port = 9999
p find_broadcast_address host, port

Port number automatically assigned by the OS

require 'socket'
require 'ipaddr'

host = IPSocket::getaddress( Socket::gethostname )

s = UDPSocket.new
s.send "dummy data", 0, host, 65535  # by sending a dummy data, the OS automatically assigns an unused port.
port = s.addr[1]
p [ "port number = ", port ]

s.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, 1)
mask = 8
23.times do 
  ip = IPAddr.new( "#{host}/#{mask}" ).to_range.max.to_s
  p "#{ip}\n"
  s.send "#{ip}\n", 0, ip, port  
  mask = mask + 1
end

p [ "broadcast address = ", s.gets ]