Class: RPing

Inherits:
Object
  • Object
show all
Defined in:
lib/rping.rb

Constant Summary collapse

MAX_LEN =
64 * 1024

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ RPing

Returns a new instance of RPing.



6
7
8
9
10
11
12
# File 'lib/rping.rb', line 6

def initialize(options = {})
  @count    = options.fetch(:count, 1)
  @interval = options.fetch(:interval, 1)
  @timeout  = options.fetch(:timeout, 4)
  @icmp_id  = (self.object_id ^  Process.pid) & 0xffff
  @seq_num  = 1
end

Class Method Details

.multi_ping(dests, options = {}) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/rping.rb', line 18

def self.multi_ping(dests, options = {})
  ths = []
  reply_h = {}

  dests.each do |dest|
    ths << Thread.start {
      reply_h[dest] = RPing.ping(dest, options)
    }
  end

  ths.each {|th| th.join }

  return reply_h
end

.ping(dest, options = {}, &block) ⇒ Object



14
15
16
# File 'lib/rping.rb', line 14

def self.ping(dest, options = {}, &block)
  self.new(options).ping(dest, &block)
end

Instance Method Details

#make_socketObject



53
54
55
# File 'lib/rping.rb', line 53

def make_socket
  Socket.new(Socket::AF_INET, Socket::SOCK_RAW, Socket::IPPROTO_ICMP)
end

#ping(addr, &block) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rping.rb', line 33

def ping(addr, &block)
  unless addr =~ /\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z/
    addr = IPSocket.getaddress(addr)
  end

  sock = nil
  buf = []

  begin
    sock = make_socket
    th = ping_recv(sock, buf, &block)
    ping_send(sock, addr)
    th.join
  ensure
    sock.close if sock
  end

  return buf
end

#ping_recv(sock, buf = nil, &block) ⇒ Object



67
68
69
70
71
72
73
74
75
76
# File 'lib/rping.rb', line 67

def ping_recv(sock, buf = nil, &block)
  Thread.start do
    @count.times do
      reply = ping_recv0(sock)
      redo if reply == :redo
      yield(reply) if block
      buf << reply if buf
    end
  end
end

#ping_send(sock, addr) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/rping.rb', line 57

def ping_send(sock, addr)
  sockaddr = Socket.pack_sockaddr_in(0, addr)

  @count.times do |i|
    sleep @interval unless i.zero?
    req = make_echo_request
    sock.send(req, 0, sockaddr)
  end
end