Class: EtherPing::Client

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

Overview

ether_ping implementation.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(eth_device, ether_type, destination_mac) ⇒ Client

Returns a new instance of Client.



8
9
10
11
12
13
# File 'lib/ether_ping/client.rb', line 8

def initialize(eth_device, ether_type, destination_mac)
  @socket = Ethernet.raw_socket eth_device, ether_type
  @source_mac = Ethernet::Devices.mac eth_device
  @dest_mac = [destination_mac].pack('H*')[0, 6]
  @ether_type = [ether_type].pack('n')    
end

Instance Attribute Details

#dest_macObject (readonly)

Returns the value of attribute dest_mac.



17
18
19
# File 'lib/ether_ping/client.rb', line 17

def dest_mac
  @dest_mac
end

#socketObject (readonly)

Returns the value of attribute socket.



15
16
17
# File 'lib/ether_ping/client.rb', line 15

def socket
  @socket
end

#source_macObject (readonly)

Returns the value of attribute source_mac.



16
17
18
# File 'lib/ether_ping/client.rb', line 16

def source_mac
  @source_mac
end

Instance Method Details

#ping(data, timeout = 1) ⇒ Object

Pings over raw Ethernet sockets.

Returns true if the ping response matches, an array of [expected, received] strings if it doesn’t match, and false if the ping times out.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/ether_ping/client.rb', line 23

def ping(data, timeout = 1)
  data = data.clone
  # Pad data to have at least 64 bytes.
  data += "\0" * (64 - data.length) if data.length < 64
 
  ping_packet = @dest_mac + @source_mac + @ether_type + data
  @socket.send ping_packet, 0

  response_packet = @source_mac + @dest_mac + @ether_type + data
  
  response = nil
  begin
    Timeout.timeout timeout do
      response = @socket.recv response_packet.length * 2
    end
  rescue Timeout::Error
    response = nil
  end
  return false unless response
  response == response_packet || [response, response_packet]
end