Class: ZeroConf::Client

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/zeroconf/client.rb

Direct Known Subclasses

Browser, Discoverer, Resolver

Constant Summary

Constants included from Utils

Utils::BROADCAST_V4, Utils::BROADCAST_V6, Utils::DISCOVERY_NAME

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utils

#broadcast_v4, #broadcast_v6, #multicast_send, #open_ipv4, #open_ipv6, #unicast_send

Constructor Details

#initialize(name, interfaces: ZeroConf.interfaces) ⇒ Client

Returns a new instance of Client.



11
12
13
14
# File 'lib/zeroconf/client.rb', line 11

def initialize name, interfaces: ZeroConf.interfaces
  @name = name
  @interfaces = interfaces
end

Instance Attribute Details

#interfacesObject (readonly)

Returns the value of attribute interfaces.



9
10
11
# File 'lib/zeroconf/client.rb', line 9

def interfaces
  @interfaces
end

#nameObject (readonly)

Returns the value of attribute name.



9
10
11
# File 'lib/zeroconf/client.rb', line 9

def name
  @name
end

Instance Method Details

#run(timeout: 3) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/zeroconf/client.rb', line 16

def run timeout: 3
  sockets = open_interfaces interfaces.map(&:addr), 0

  query = get_query
  sockets.each { |socket| multicast_send(socket, query.encode) }

  start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  now = start
  msgs = block_given? ? nil : []

  loop do
    wait = timeout && timeout - (now - start)
    return if wait && wait < 0

    readers, = IO.select(sockets, [], [], wait)

    return msgs unless readers

    readers.each do |reader|
      buf, _ = reader.recvfrom 2048
      msg = Resolv::DNS::Message.decode(buf)
      # only yield replies to this question
      if interested? msg
        if block_given?
          if :done == yield(msg)
            return msg
          end
        else
          msgs << msg
        end
      end
    end
    now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  end
ensure
  sockets.each(&:close) if sockets
end