Skip to content

attempts of obtaining a broadcast address

tora edited this page Jul 4, 2012 · 6 revisions
## Using select()
require 'socket'
require 'ipaddr'

def get_broadcast_address host, port
  s = UDPSocket.new
  s.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, 1)
  s.bind "0.0.0.0", port
  (8..31).each do |mask|
    ip = IPAddr.new( "#{host}/#{mask}" ).to_range.max.to_s
    # p "#{ip}\n"
    s.send "#{ip}\n", 0, ip, port  
    select( [s], nil, nil, 0.01 ) and return ip
  end
  nil
ensure
  s.close
end

host = IPSocket::getaddress( Socket::gethostname )
port = 9999
p get_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 ]