Skip to content

Instantly share code, notes, and snippets.

@oogali
Created April 7, 2013 17:31
Show Gist options
  • Save oogali/5331457 to your computer and use it in GitHub Desktop.
Save oogali/5331457 to your computer and use it in GitHub Desktop.
Joining a multicast group with Ruby
#!/usr/bin/env ruby
require 'rubygems'
require 'socket'
require 'ipaddr'
MCAST_GROUP = {
:addr => '224.5.6.7',
:port => 12345,
:bindaddr => '192.168.1.2'
}
ip = IPAddr.new(MCAST_GROUP[:addr]).hton + IPAddr.new(MCAST_GROUP[:bindaddr]).hton
begin
sock = UDPSocket.open
sock.setsockopt Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, ip
sock.bind Socket::INADDR_ANY, MCAST_GROUP[:port]
loop do
msg, info = sock.recvfrom(1024)
puts "MSG: #{msg} from #{info[2]} (#{info[3]})/#{info[1]} len #{msg.size}"
end
ensure
sock.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment